2 * Copyright (c) 2002 Juli Mallett.
3 * Copyright (c) 1988, 1989, 1990, 1993
4 * The Regents of the University of California. All rights reserved.
5 * Copyright (c) 1989 by Berkeley Softworks
8 * This code is derived from software contributed to Berkeley by
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 * @(#)var.c 8.3 (Berkeley) 3/19/94
40 * $FreeBSD: src/usr.bin/make/var.c,v 1.83 2005/02/11 10:49:01 harti Exp $
41 * $DragonFly: src/usr.bin/make/var.c,v 1.224 2005/09/24 07:37:38 okumoto Exp $
46 * Variable-handling functions
49 * Var_Set Set the value of a variable in the given
50 * context. The variable is created if it doesn't
51 * yet exist. The value and variable name need not
54 * Var_Append Append more characters to an existing variable
55 * in the given context. The variable needn't
56 * exist already -- it will be created if it doesn't.
57 * A space is placed between the old value and the
60 * Var_Value Return the value of a variable in a context or
61 * NULL if the variable is undefined.
63 * Var_Subst Substitute named variable, or all variables if
64 * NULL in a string using
65 * the given context as the top-most one. If the
66 * third argument is non-zero, Parse_Error is
67 * called if any variables are undefined.
69 * Var_Parse Parse a variable expansion from a string and
70 * return the result and the number of characters
73 * Var_Delete Delete a variable in a context.
75 * Var_Init Initialize this module.
78 * Var_Dump Print out all variables defined in the given
81 * XXX: There's a lot of duplication in these functions.
88 #include <sys/types.h>
107 typedef struct VarParser
{
108 const char *const input
; /* pointer to input string */
109 const char *ptr
; /* current parser pos in input str */
116 char *name
; /* the variable's name */
117 struct Buffer
*val
; /* its value */
118 int flags
; /* miscellaneous status flags */
120 #define VAR_IN_USE 1 /* Variable's value currently being used.
121 * Used to avoid recursion */
123 #define VAR_JUNK 4 /* Variable is a junk variable that
124 * should be destroyed when done with
125 * it. Used by Var_Parse for undefined,
126 * modified variables */
128 #define VAR_TO_ENV 8 /* Place variable in environment */
132 struct Buffer
*lhs
; /* String to match */
133 struct Buffer
*rhs
; /* Replacement string (w/ &'s removed) */
140 #define VAR_SUB_GLOBAL 0x01 /* Apply substitution globally */
141 #define VAR_SUB_ONE 0x02 /* Apply substitution to one word */
142 #define VAR_SUB_MATCHED 0x04 /* There was a match */
143 #define VAR_MATCH_START 0x08 /* Match at start of word */
144 #define VAR_MATCH_END 0x10 /* Match at end of word */
147 typedef bool VarModifyProc(const char [], bool, struct Buffer
*, void *);
149 static char *VarParse(VarParser
*, bool *);
152 * This is a harmless return value for Var_Parse that can be used by Var_Subst
153 * to determine if there was an error in parsing -- easier than returning
154 * a flag, as things outside this module don't give a hoot.
156 char var_Error
[] = "";
159 * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
160 * set false. Why not just use a constant? Well, gcc likes to condense
161 * identical string instances...
163 static char varNoError
[] = "";
166 * Internally, variables are contained in four different contexts.
167 * 1) the environment. They may not be changed. If an environment
168 * variable is appended-to, the result is placed in the global
170 * 2) the global context. Variables set in the Makefile are located in
171 * the global context. It is the penultimate context searched when
173 * 3) the command-line context. All variables set on the command line
174 * are placed in this context. They are UNALTERABLE once placed here.
175 * 4) the local context. Each target has associated with it a context
176 * list. On this list are located the structures describing such
177 * local variables as $(@) and $(*)
178 * The four contexts are searched in the reverse order from which they are
181 static GNode
*VAR_ENV
; /* variables from the environment */
182 GNode
*VAR_GLOBAL
; /* variables from the makefile */
183 GNode
*VAR_CMD
; /* variables defined on the command-line */
185 bool oldVars
; /* variable substitution style */
186 bool checkEnvFirst
; /* -e flag */
189 * Create a Var object.
191 * @param name Name of variable.
192 * @param value Value of variable.
193 * @param flags Flags set on variable.
196 VarCreate(const char name
[], const char value
[], int flags
)
200 v
= emalloc(sizeof(Var
));
201 v
->name
= estrdup(name
);
202 v
->val
= Buf_Init(0);
206 Buf_Append(v
->val
, value
);
212 * Destroy a Var object.
214 * @param v Object to destroy.
215 * @param f true if internal buffer in Buffer object is to be
219 VarDestroy(Var
*v
, bool f
)
222 Buf_Destroy(v
->val
, f
);
228 * Remove the tail of the given word and place the result in the given
232 * true if characters were added to the buffer (a space needs to be
233 * added to the buffer before the next word).
236 * The trimmed word is added to the buffer.
239 VarHead(const char word
[], bool addSpace
, Buffer
*buf
, void *dummy __unused
)
243 slash
= strrchr(word
, '/');
246 Buf_AddByte(buf
, ' ');
248 Buf_AppendRange(buf
, word
, slash
);
251 * If no directory part, give . (q.v. the POSIX standard)
254 Buf_Append(buf
, " .");
256 Buf_AddByte(buf
, '.');
263 * Remove the head of the given word and place the result in the given
267 * true if characters were added to the buffer (a space needs to be
268 * added to the buffer before the next word).
271 * The trimmed word is added to the buffer.
274 VarTail(const char word
[], bool addSpace
, Buffer
*buf
, void *dummy __unused
)
279 Buf_AddByte(buf
, ' ');
282 slash
= strrchr(word
, '/');
285 Buf_Append(buf
, slash
);
287 Buf_Append(buf
, word
);
293 * Place the suffix of the given word in the given buffer.
296 * true if characters were added to the buffer (a space needs to be
297 * added to the buffer before the next word).
300 * The suffix from the word is placed in the buffer.
303 VarSuffix(const char word
[], bool addSpace
, Buffer
*buf
, void *dummy __unused
)
307 dot
= strrchr(word
, '.');
310 Buf_AddByte(buf
, ' ');
313 Buf_Append(buf
, dot
);
320 * Remove the suffix of the given word and place the result in the
324 * true if characters were added to the buffer (a space needs to be
325 * added to the buffer before the next word).
328 * The trimmed word is added to the buffer.
331 VarRoot(const char word
[], bool addSpace
, Buffer
*buf
, void *dummy __unused
)
336 Buf_AddByte(buf
, ' ');
339 dot
= strrchr(word
, '.');
341 Buf_AppendRange(buf
, word
, dot
);
343 Buf_Append(buf
, word
);
349 * Place the word in the buffer if it matches the given pattern.
350 * Callback function for VarModify to implement the :M modifier.
351 * A space will be added if requested. A pattern is supplied
352 * which the word must match.
355 * true if a space should be placed in the buffer before the next
359 * The word may be copied to the buffer.
362 VarMatch(const char word
[], bool addSpace
, Buffer
*buf
, void *pattern
)
365 if (Str_Match(word
, pattern
)) {
367 Buf_AddByte(buf
, ' ');
370 Buf_Append(buf
, word
);
376 * Place the word in the buffer if it matches the given pattern.
377 * Callback function for VarModify to implement the System V %
378 * modifiers. A space is added if requested.
381 * true if a space should be placed in the buffer before the next
385 * The word may be copied to the buffer.
388 VarSYSVMatch(const char word
[], bool addSpace
, Buffer
*buf
, void *patp
)
392 VarPattern
*pat
= (VarPattern
*)patp
;
395 Buf_AddByte(buf
, ' ');
399 if ((ptr
= Str_SYSVMatch(word
, Buf_Data(pat
->lhs
), &len
)) != NULL
)
400 Str_SYSVSubst(buf
, Buf_Data(pat
->rhs
), ptr
, len
);
402 Buf_Append(buf
, word
);
408 * Place the word in the buffer if it doesn't match the given pattern.
409 * Callback function for VarModify to implement the :N modifier. A
410 * space is added if requested.
413 * true if a space should be placed in the buffer before the next
417 * The word may be copied to the buffer.
420 VarNoMatch(const char word
[], bool addSpace
, Buffer
*buf
, void *pattern
)
423 if (!Str_Match(word
, pattern
)) {
425 Buf_AddByte(buf
, ' ');
428 Buf_Append(buf
, word
);
434 * Perform a string-substitution on the given word, placing the
435 * result in the passed buffer. A space is added if requested.
438 * true if a space is needed before more characters are added.
441 VarSubstitute(const char word
[], bool addSpace
, Buffer
*buf
, void *patternp
)
443 size_t wordLen
; /* Length of word */
444 const char *cp
; /* General pointer */
445 VarPattern
*pattern
= patternp
;
447 wordLen
= strlen(word
);
448 if (1) { /* substitute in each word of the variable */
450 * Break substitution down into simple anchored cases
451 * and if none of them fits, perform the general substitution
454 if ((pattern
->flags
& VAR_MATCH_START
) &&
455 (strncmp(word
, Buf_Data(pattern
->lhs
),
456 Buf_Size(pattern
->lhs
)) == 0)) {
458 * Anchored at start and beginning of word matches
461 if ((pattern
->flags
& VAR_MATCH_END
) &&
462 (wordLen
== Buf_Size(pattern
->lhs
))) {
464 * Also anchored at end and matches to the end
465 * (word is same length as pattern) add space
466 * and rhs only if rhs is non-null.
468 if (Buf_Size(pattern
->rhs
) != 0) {
470 Buf_AddByte(buf
, ' ');
473 Buf_AppendBuf(buf
, pattern
->rhs
);
476 } else if (pattern
->flags
& VAR_MATCH_END
) {
478 * Doesn't match to end -- copy word wholesale
484 * Matches at start but need to copy in
485 * trailing characters.
487 if ((Buf_Size(pattern
->rhs
) + wordLen
-
488 Buf_Size(pattern
->lhs
)) != 0) {
490 Buf_AddByte(buf
, ' ');
494 Buf_AppendBuf(buf
, pattern
->rhs
);
495 Buf_AddBytes(buf
, wordLen
-
496 Buf_Size(pattern
->lhs
),
497 (word
+ Buf_Size(pattern
->lhs
)));
500 } else if (pattern
->flags
& VAR_MATCH_START
) {
502 * Had to match at start of word and didn't -- copy
507 } else if (pattern
->flags
& VAR_MATCH_END
) {
509 * Anchored at end, Find only place match could occur
510 * (leftLen characters from the end of the word) and
511 * see if it does. Note that because the $ will be
512 * left at the end of the lhs, we have to use strncmp.
514 cp
= word
+ (wordLen
- Buf_Size(pattern
->lhs
));
515 if ((cp
>= word
) && (strncmp(cp
, Buf_Data(pattern
->lhs
),
516 Buf_Size(pattern
->lhs
)) == 0)) {
518 * Match found. If we will place characters in
519 * the buffer, add a space before hand as
520 * indicated by addSpace, then stuff in the
521 * initial, unmatched part of the word followed
522 * by the right-hand-side.
524 if ((cp
- word
) + Buf_Size(pattern
->rhs
) != 0) {
526 Buf_AddByte(buf
, ' ');
530 Buf_AppendRange(buf
, word
, cp
);
531 Buf_AppendBuf(buf
, pattern
->rhs
);
535 * Had to match at end and didn't. Copy entire
542 * Pattern is unanchored: search for the pattern in the
543 * word using strstr(3), copying unmatched portions and
544 * the right-hand-side for each match found, handling
545 * non-global substitutions correctly, etc. When the
546 * loop is done, any remaining part of the word (word
547 * and wordLen are adjusted accordingly through the
548 * loop) is copied straight into the buffer.
549 * addSpace is set false as soon as a space is added
556 origSize
= Buf_Size(buf
);
558 cp
= strstr(word
, Buf_Data(pattern
->lhs
));
560 if (addSpace
&& (((cp
- word
) +
561 Buf_Size(pattern
->rhs
)) != 0)) {
562 Buf_AddByte(buf
, ' ');
565 Buf_AppendRange(buf
, word
, cp
);
566 Buf_AppendBuf(buf
, pattern
->rhs
);
567 wordLen
-= (cp
- word
) +
568 Buf_Size(pattern
->lhs
);
569 word
= cp
+ Buf_Size(pattern
->lhs
);
570 if (wordLen
== 0 || (pattern
->flags
&
571 VAR_SUB_GLOBAL
) == 0) {
580 Buf_AddByte(buf
, ' ');
582 Buf_AddBytes(buf
, wordLen
, word
);
586 * If added characters to the buffer, need to add a
587 * space before we add any more. If we didn't add any,
588 * just return the previous value of addSpace.
590 return ((Buf_Size(buf
) != origSize
) || addSpace
);
593 * Common code for anchored substitutions:
594 * addSpace was set true if characters were added to the buffer.
600 Buf_AddByte(buf
, ' ');
602 Buf_AddBytes(buf
, wordLen
, word
);
607 * Print the error caused by a regcomp or regexec call.
610 * An error gets printed.
613 VarREError(int err
, regex_t
*pat
, const char str
[])
618 errlen
= regerror(err
, pat
, 0, 0);
619 errbuf
= emalloc(errlen
);
620 regerror(err
, pat
, errbuf
, errlen
);
621 Error("%s: %s", str
, errbuf
);
627 * Perform a regex substitution on the given word, placing the
628 * result in the passed buffer. A space is added if requested.
631 * true if a space is needed before more characters are added.
634 VarRESubstitute(const char word
[], bool addSpace
, Buffer
*buf
, void *patternp
)
643 #define MAYBE_ADD_SPACE() \
644 if (addSpace && !added) \
645 Buf_AddByte(buf, ' '); \
652 if ((pat
->flags
& (VAR_SUB_ONE
| VAR_SUB_MATCHED
)) ==
653 (VAR_SUB_ONE
| VAR_SUB_MATCHED
)) {
657 xrv
= regexec(&pat
->re
, wp
, pat
->nsub
, pat
->matches
, flags
);
662 pat
->flags
|= VAR_SUB_MATCHED
;
663 if (pat
->matches
[0].rm_so
> 0) {
665 Buf_AddBytes(buf
, pat
->matches
[0].rm_so
, wp
);
668 for (rp
= Buf_Data(pat
->rhs
); *rp
; rp
++) {
669 if ((*rp
== '\\') && ((rp
[1] == '&') || (rp
[1] == '\\'))) {
671 Buf_AddByte(buf
, rp
[1]);
674 } else if ((*rp
== '&') ||
675 ((*rp
== '\\') && isdigit((unsigned char)rp
[1]))) {
694 Error("No subexpression %s",
699 } else if ((pat
->matches
[n
].rm_so
== -1) &&
700 (pat
->matches
[n
].rm_eo
== -1)) {
701 Error("No match for subexpression %s",
707 subbuf
= wp
+ pat
->matches
[n
].rm_so
;
708 sublen
= pat
->matches
[n
].rm_eo
-
709 pat
->matches
[n
].rm_so
;
714 Buf_AddBytes(buf
, sublen
, subbuf
);
718 Buf_AddByte(buf
, *rp
);
721 wp
+= pat
->matches
[0].rm_eo
;
722 if (pat
->flags
& VAR_SUB_GLOBAL
) {
724 if (pat
->matches
[0].rm_so
== 0 &&
725 pat
->matches
[0].rm_eo
== 0) {
727 Buf_AddByte(buf
, *wp
);
740 VarREError(xrv
, &pat
->re
, "Unexpected regex error");
750 return (addSpace
|| added
);
754 * Find a variable in a variable list.
757 VarLookup(Lst
*vlist
, const char name
[])
761 LST_FOREACH(ln
, vlist
)
762 if (strcmp(((const Var
*)Lst_Datum(ln
))->name
, name
) == 0)
763 return (Lst_Datum(ln
));
768 * Expand a variable name's embedded variables in the given context.
771 * The contents of name, possibly expanded.
774 VarPossiblyExpand(const char name
[], GNode
*ctxt
)
778 if (strchr(name
, '$') != NULL
) {
779 buf
= Var_Subst(name
, ctxt
, 0);
780 return (Buf_Peel(buf
));
782 return estrdup(name
);
787 * If the variable name begins with a '.', it could very well be
788 * one of the local ones. We check the name against all the local
789 * variables and substitute the short version in for 'name' if it
790 * matches one of them.
793 VarLocal(const char name
[])
795 if (name
[0] == '.') {
798 if (!strcmp(name
, ".ALLSRC"))
800 if (!strcmp(name
, ".ARCHIVE"))
804 if (!strcmp(name
, ".IMPSRC"))
808 if (!strcmp(name
, ".MEMBER"))
812 if (!strcmp(name
, ".OODATE"))
816 if (!strcmp(name
, ".PREFIX"))
820 if (!strcmp(name
, ".TARGET"))
831 * Find the given variable in the given context and the environment.
834 * A pointer to the structure describing the desired variable or
835 * NULL if the variable does not exist.
838 VarFindEnv(const char name
[], GNode
*ctxt
)
842 name
= VarLocal(name
);
844 if ((var
= VarLookup(&ctxt
->context
, name
)) != NULL
)
847 if ((var
= VarLookup(&VAR_ENV
->context
, name
)) != NULL
)
854 * Look for the variable in the given context.
857 VarFindOnly(const char name
[], GNode
*ctxt
)
860 return (VarLookup(&ctxt
->context
, VarLocal(name
)));
864 * Look for the variable in all contexts.
867 VarFindAny(const char name
[], GNode
*ctxt
)
869 bool localCheckEnvFirst
;
873 name
= VarLocal(name
);
876 * Note whether this is one of the specific variables we were told
877 * through the -E flag to use environment-variable-override for.
879 localCheckEnvFirst
= false;
880 LST_FOREACH(ln
, &envFirstVars
) {
881 if (strcmp(Lst_Datum(ln
), name
) == 0) {
882 localCheckEnvFirst
= true;
888 * First look for the variable in the given context. If it's not there,
889 * look for it in VAR_CMD, VAR_GLOBAL and the environment,
890 * in that order, depending on the FIND_* flags in 'flags'
892 if ((var
= VarLookup(&ctxt
->context
, name
)) != NULL
)
895 /* not there - try command line context */
896 if (ctxt
!= VAR_CMD
) {
897 if ((var
= VarLookup(&VAR_CMD
->context
, name
)) != NULL
)
901 /* not there - try global context, but only if not -e/-E */
902 if (ctxt
!= VAR_GLOBAL
&& (!checkEnvFirst
&& !localCheckEnvFirst
)) {
903 if ((var
= VarLookup(&VAR_GLOBAL
->context
, name
)) != NULL
)
907 if ((var
= VarLookup(&VAR_ENV
->context
, name
)) != NULL
)
910 /* deferred check for the environment (in case of -e/-E) */
911 if ((ctxt
!= VAR_GLOBAL
) && (checkEnvFirst
|| localCheckEnvFirst
)) {
912 if ((var
= VarLookup(&VAR_GLOBAL
->context
, name
)) != NULL
)
920 * Add a new variable of name name and value val to the given context.
923 * The new variable is placed at the front of the given context
924 * The name and val arguments are duplicated so they may
928 VarAdd(const char name
[], const char val
[], GNode
*ctxt
)
931 Lst_AtFront(&ctxt
->context
, VarCreate(name
, val
, 0));
932 DEBUGF(VAR
, ("%s:%s = %s\n", ctxt
->name
, name
, val
));
936 * Remove a variable from a context.
939 * The Var structure is removed and freed.
942 Var_Delete(const char name
[], GNode
*ctxt
)
946 DEBUGF(VAR
, ("%s:delete %s\n", ctxt
->name
, name
));
947 LST_FOREACH(ln
, &ctxt
->context
) {
948 if (strcmp(((const Var
*)Lst_Datum(ln
))->name
, name
) == 0) {
949 VarDestroy(Lst_Datum(ln
), true);
950 Lst_Remove(&ctxt
->context
, ln
);
957 * Set the variable name to the value val in the given context.
960 * If the variable doesn't yet exist, a new record is created for it.
961 * Else the old value is freed and the new one stuck in its place
964 * The variable is searched for only in its context before being
965 * created in that context. I.e. if the context is VAR_GLOBAL,
966 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
967 * VAR_CMD->context is searched. This is done to avoid the literally
968 * thousands of unnecessary strcmp's that used to be done to
969 * set, say, $(@) or $(<).
972 Var_Set(const char name
[], const char val
[], GNode
*ctxt
)
978 * We only look for a variable in the given context since anything
979 * set here will override anything in a lower context, so there's not
980 * much point in searching them all just to save a bit of memory...
982 n
= VarPossiblyExpand(name
, ctxt
);
983 v
= VarFindOnly(n
, ctxt
);
985 VarAdd(n
, val
, ctxt
);
986 if (ctxt
== VAR_CMD
) {
988 * Any variables given on the command line
989 * are automatically exported to the
990 * environment (as per POSIX standard)
992 if (setenv(n
, val
, 1) == -1)
993 Punt( "setenv: %s: can't allocate memory", n
);
997 Buf_Append(v
->val
, val
);
999 if (ctxt
== VAR_CMD
|| (v
->flags
& VAR_TO_ENV
)) {
1001 * Any variables given on the command line
1002 * are automatically exported to the
1003 * environment (as per POSIX standard)
1007 exp_value
= Buf_Peel(Var_Subst(val
, ctxt
, false));
1008 if (setenv(n
, exp_value
, 1) == -1)
1009 Punt( "setenv: %s: can't allocate memory", n
);
1015 DEBUGF(VAR
, ("%s:%s = %s\n", ctxt
->name
, n
, val
));
1020 * Set the a global name variable to the value.
1023 Var_SetGlobal(const char name
[], const char value
[])
1026 Var_Set(name
, value
, VAR_GLOBAL
);
1031 * Set the VAR_TO_ENV flag on a variable
1034 Var_SetEnv(const char name
[], GNode
*ctxt
)
1038 v
= VarFindOnly(name
, VAR_CMD
);
1041 * Do not allow .EXPORT: to be set on variables
1042 * from the command line or MAKEFLAGS.
1045 "Warning: Did not set .EXPORTVAR: on %s because it "
1046 "is from the command line or MAKEFLAGS", name
);
1050 v
= VarFindAny(name
, ctxt
);
1052 Lst_AtFront(&VAR_ENV
->context
,
1053 VarCreate(name
, NULL
, VAR_TO_ENV
));
1054 if (setenv(name
, "", 1) == -1)
1055 Punt( "setenv: %s: can't allocate memory", name
);
1056 Error("Warning: .EXPORTVAR: set on undefined variable %s", name
);
1058 if ((v
->flags
& VAR_TO_ENV
) == 0) {
1061 value
= Buf_Peel(Var_Subst(Buf_Data(v
->val
), ctxt
, false));
1062 v
->flags
|= VAR_TO_ENV
;
1063 if (setenv(v
->name
, value
, 1) == -1)
1064 Punt( "setenv: %s: can't allocate memory", v
->name
);
1071 * The variable of the given name has the given value appended to it in
1072 * the given context.
1075 * If the variable doesn't exist, it is created. Else the strings
1076 * are concatenated (with a space in between).
1079 * Only if the variable is being sought in the global context is the
1080 * environment searched.
1081 * XXX: Knows its calling circumstances in that if called with ctxt
1082 * an actual target, it will only search that context since only
1083 * a local variable could be being appended to. This is actually
1084 * a big win and must be tolerated.
1087 Var_Append(const char name
[], const char val
[], GNode
*ctxt
)
1092 n
= VarPossiblyExpand(name
, ctxt
);
1093 if (ctxt
== VAR_GLOBAL
) {
1094 v
= VarFindEnv(n
, ctxt
);
1096 v
= VarFindOnly(n
, ctxt
);
1099 VarAdd(n
, val
, ctxt
);
1101 Buf_AddByte(v
->val
, ' ');
1102 Buf_Append(v
->val
, val
);
1103 DEBUGF(VAR
, ("%s:%s = %s\n", ctxt
->name
, n
, Buf_Data(v
->val
)));
1109 * Return the value of the named variable in the given context
1112 * The value if the variable exists, NULL if it doesn't.
1115 Var_Value(const char name
[], GNode
*ctxt
)
1120 n
= VarPossiblyExpand(name
, ctxt
);
1121 v
= VarFindAny(n
, ctxt
);
1126 return (Buf_Data(v
->val
));
1131 * Modify each of the words of the passed string using the given
1132 * function. Used to implement all modifiers.
1135 * A string of all the words modified appropriately.
1138 VarModify(const char str
[], VarModifyProc
*modProc
, void *datum
)
1141 Buffer
*buf
; /* Buffer for the new string */
1144 * true if need to add a space to
1145 * the buffer before adding the
1149 brk_string(&aa
, str
, false);
1153 for (i
= 1; i
< aa
.argc
; i
++)
1154 addSpace
= (*modProc
)(aa
.argv
[i
], addSpace
, buf
, datum
);
1157 return (Buf_Peel(buf
));
1161 * Sort the words in the string.
1164 * str String whose words should be sorted
1165 * cmp A comparison function to control the ordering
1168 * A string containing the words sorted
1171 VarSortWords(const char str
[], int (*cmp
)(const void *, const void *))
1177 brk_string(&aa
, str
, false);
1178 qsort(aa
.argv
+ 1, aa
.argc
- 1, sizeof(char *), cmp
);
1181 for (i
= 1; i
< aa
.argc
; i
++) {
1182 Buf_Append(buf
, aa
.argv
[i
]);
1183 Buf_AddByte(buf
, ((i
< aa
.argc
- 1) ? ' ' : '\0'));
1187 return (Buf_Peel(buf
));
1191 SortIncreasing(const void *l
, const void *r
)
1194 return (strcmp(*(const char* const*)l
, *(const char* const*)r
));
1198 * Pass through the tstr looking for 1) escaped delimiters,
1199 * '$'s and backslashes (place the escaped character in
1200 * uninterpreted) and 2) unescaped $'s that aren't before
1201 * the delimiter (expand the variable substitution).
1202 * Return the expanded string or NULL if the delimiter was missing
1203 * If pattern is specified, handle escaped ampersands, and replace
1204 * unescaped ampersands with the lhs of the pattern.
1207 * A string of all the words modified appropriately.
1208 * If length is specified, return the string length of the buffer
1209 * If flags is specified and the last character of the pattern is a
1210 * $ set the VAR_MATCH_END bit of flags.
1213 VarGetPattern(VarParser
*vp
, int delim
, int *flags
, VarPattern
*patt
)
1220 * Skim through until the matching delimiter is found; pick up
1221 * variable substitutions on the way. Also allow backslashes to quote
1222 * the delimiter, $, and \, but don't touch other backslashes.
1224 while (*vp
->ptr
!= '\0') {
1225 if (*vp
->ptr
== delim
) {
1228 } else if ((vp
->ptr
[0] == '\\') &&
1229 ((vp
->ptr
[1] == delim
) ||
1230 (vp
->ptr
[1] == '\\') ||
1231 (vp
->ptr
[1] == '$') ||
1232 (vp
->ptr
[1] == '&' && patt
!= NULL
))) {
1233 vp
->ptr
++; /* consume backslash */
1234 Buf_AddByte(buf
, vp
->ptr
[0]);
1237 } else if (vp
->ptr
[0] == '$') {
1238 if (vp
->ptr
[1] == delim
) {
1239 if (flags
== NULL
) {
1240 Buf_AddByte(buf
, vp
->ptr
[0]);
1244 * Unescaped $ at end of patt =>
1245 * anchor patt at end.
1247 *flags
|= VAR_MATCH_END
;
1262 * If unescaped dollar sign not
1263 * before the delimiter, assume it's
1264 * a variable substitution and
1267 rval
= VarParse(&subvp
, &rfree
);
1268 Buf_Append(buf
, rval
);
1271 vp
->ptr
= subvp
.ptr
;
1273 } else if (vp
->ptr
[0] == '&' && patt
!= NULL
) {
1274 Buf_AppendBuf(buf
, patt
->lhs
);
1277 Buf_AddByte(buf
, vp
->ptr
[0]);
1282 Buf_Destroy(buf
, true);
1287 * Make sure this variable is fully expanded.
1290 VarExpand(Var
*v
, VarParser
*vp
)
1295 if (v
->flags
& VAR_IN_USE
) {
1296 Fatal("Variable %s is recursive.", v
->name
);
1300 v
->flags
|= VAR_IN_USE
;
1303 * Before doing any modification, we have to make sure the
1304 * value has been fully expanded. If it looks like recursion
1305 * might be necessary (there's a dollar sign somewhere in the
1306 * variable's value) we just call Var_Subst to do any other
1307 * substitutions that are necessary. Note that the value
1308 * returned by Var_Subst will have been
1309 * dynamically-allocated, so it will need freeing when we
1312 value
= Buf_Data(v
->val
);
1313 if (strchr(value
, '$') == NULL
) {
1314 result
= strdup(value
);
1318 buf
= Var_Subst(value
, vp
->ctxt
, vp
->err
);
1319 result
= Buf_Peel(buf
);
1322 v
->flags
&= ~VAR_IN_USE
;
1328 * Select only those words in value that match the modifier.
1331 modifier_M(VarParser
*vp
, const char value
[], char endc
)
1338 modifier
= vp
->ptr
[0];
1339 vp
->ptr
++; /* consume 'M' or 'N' */
1342 * Compress the \:'s out of the pattern, so allocate enough
1343 * room to hold the uncompressed pattern and compress the
1344 * pattern into that space.
1346 patt
= estrdup(vp
->ptr
);
1348 while (vp
->ptr
[0] != '\0') {
1349 if (vp
->ptr
[0] == endc
|| vp
->ptr
[0] == ':') {
1352 if (vp
->ptr
[0] == '\\' &&
1353 (vp
->ptr
[1] == endc
|| vp
->ptr
[1] == ':')) {
1354 vp
->ptr
++; /* consume backslash */
1362 if (modifier
== 'M') {
1363 newValue
= VarModify(value
, VarMatch
, patt
);
1365 newValue
= VarModify(value
, VarNoMatch
, patt
);
1373 * Substitute the replacement string for the pattern. The substitution
1374 * is applied to each word in value.
1377 modifier_S(VarParser
*vp
, const char value
[], Var
*v
)
1385 vp
->ptr
++; /* consume 'S' */
1387 delim
= *vp
->ptr
; /* used to find end of pattern */
1388 vp
->ptr
++; /* consume 1st delim */
1391 * If pattern begins with '^', it is anchored to the start of the
1392 * word -- skip over it and flag pattern.
1394 if (*vp
->ptr
== '^') {
1395 patt
.flags
|= VAR_MATCH_START
;
1399 patt
.lhs
= VarGetPattern(vp
, delim
, &patt
.flags
, NULL
);
1400 if (patt
.lhs
== NULL
) {
1402 * LHS didn't end with the delim, complain and exit.
1404 Fatal("Unclosed substitution for %s (%c missing)",
1408 vp
->ptr
++; /* consume 2nd delim */
1410 patt
.rhs
= VarGetPattern(vp
, delim
, NULL
, &patt
);
1411 if (patt
.rhs
== NULL
) {
1413 * RHS didn't end with the delim, complain and exit.
1415 Fatal("Unclosed substitution for %s (%c missing)",
1419 vp
->ptr
++; /* consume last delim */
1422 * Check for global substitution. If 'g' after the final delimiter,
1423 * substitution is global and is marked that way.
1425 if (vp
->ptr
[0] == 'g') {
1426 patt
.flags
|= VAR_SUB_GLOBAL
;
1431 * Global substitution of the empty string causes an infinite number
1432 * of matches, unless anchored by '^' (start of string) or '$' (end
1433 * of string). Catch the infinite substitution here. Note that flags
1434 * can only contain the 3 bits we're interested in so we don't have
1435 * to mask unrelated bits. We can test for equality.
1437 if (Buf_Size(patt
.lhs
) == 0 && patt
.flags
== VAR_SUB_GLOBAL
)
1438 Fatal("Global substitution of the empty string");
1440 newValue
= VarModify(value
, VarSubstitute
, &patt
);
1443 * Free the two strings.
1452 modifier_C(VarParser
*vp
, char value
[], Var
*v
)
1461 vp
->ptr
++; /* consume 'C' */
1463 delim
= *vp
->ptr
; /* delimiter between sections */
1465 vp
->ptr
++; /* consume 1st delim */
1467 patt
.lhs
= VarGetPattern(vp
, delim
, NULL
, NULL
);
1468 if (patt
.lhs
== NULL
) {
1469 Fatal("Unclosed substitution for %s (%c missing)",
1473 vp
->ptr
++; /* consume 2st delim */
1475 patt
.rhs
= VarGetPattern(vp
, delim
, NULL
, NULL
);
1476 if (patt
.rhs
== NULL
) {
1477 Fatal("Unclosed substitution for %s (%c missing)",
1481 vp
->ptr
++; /* consume last delim */
1485 patt
.flags
|= VAR_SUB_GLOBAL
;
1486 vp
->ptr
++; /* consume 'g' */
1489 patt
.flags
|= VAR_SUB_ONE
;
1490 vp
->ptr
++; /* consume '1' */
1496 error
= regcomp(&patt
.re
, Buf_Data(patt
.lhs
), REG_EXTENDED
);
1498 VarREError(error
, &patt
.re
, "RE substitution error");
1504 patt
.nsub
= patt
.re
.re_nsub
+ 1;
1509 patt
.matches
= emalloc(patt
.nsub
* sizeof(regmatch_t
));
1511 newValue
= VarModify(value
, VarRESubstitute
, &patt
);
1522 sysVvarsub(VarParser
*vp
, char startc
, Var
*v
, const char value
[])
1525 * This can either be a bogus modifier or a System-V substitution
1535 endc
= (startc
== OPEN_PAREN
) ? CLOSE_PAREN
: CLOSE_BRACE
;
1540 * First we make a pass through the string trying to verify it is a
1541 * SYSV-make-style translation: it must be: <string1>=<string2>)
1546 while (*cp
!= '\0' && cnt
) {
1549 /* continue looking for endc */
1550 } else if (*cp
== endc
)
1552 else if (*cp
== startc
)
1558 if (*cp
== endc
&& eqFound
) {
1560 * Now we break this sucker into the lhs and rhs.
1562 patt
.lhs
= VarGetPattern(vp
, '=', &patt
.flags
, NULL
);
1563 if (patt
.lhs
== NULL
) {
1564 Fatal("Unclosed substitution for %s (%c missing)",
1567 vp
->ptr
++; /* consume '=' */
1569 patt
.rhs
= VarGetPattern(vp
, endc
, NULL
, &patt
);
1570 if (patt
.rhs
== NULL
) {
1571 Fatal("Unclosed substitution for %s (%c missing)",
1576 * SYSV modifications happen through the whole string. Note
1577 * the pattern is anchored at the end.
1579 newStr
= VarModify(value
, VarSYSVMatch
, &patt
);
1584 Error("Unknown modifier '%c'\n", *vp
->ptr
);
1586 while (*vp
->ptr
!= '\0') {
1587 if (*vp
->ptr
== endc
&& *vp
->ptr
== ':') {
1599 * Quote shell meta-characters in the string
1605 Var_Quote(const char str
[])
1608 /* This should cover most shells :-( */
1609 static char meta
[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
1611 buf
= Buf_Init(MAKE_BSIZE
);
1612 for (; *str
; str
++) {
1613 if (strchr(meta
, *str
) != NULL
)
1614 Buf_AddByte(buf
, '\\');
1615 Buf_AddByte(buf
, *str
);
1618 return (Buf_Peel(buf
));
1623 * Now we need to apply any modifiers the user wants applied.
1626 * words which match the given <pattern>.
1627 * <pattern> is of the standard file
1629 * :S<d><pat1><d><pat2><d>[g]
1630 * Substitute <pat2> for <pat1> in the value
1631 * :C<d><pat1><d><pat2><d>[g]
1632 * Substitute <pat2> for regex <pat1> in the value
1633 * :H Substitute the head of each word
1634 * :T Substitute the tail of each word
1635 * :E Substitute the extension (minus '.') of
1637 * :R Substitute the root of each word
1638 * (pathname minus the suffix).
1640 * Like :S, but the rhs goes to the end of
1642 * :U Converts variable to upper-case.
1643 * :L Converts variable to lower-case.
1645 * XXXHB update this comment or remove it and point to the man page.
1648 ParseModifier(VarParser
*vp
, char startc
, Var
*v
, bool *freeResult
)
1653 value
= VarExpand(v
, vp
);
1656 endc
= (startc
== OPEN_PAREN
) ? CLOSE_PAREN
: CLOSE_BRACE
;
1658 vp
->ptr
++; /* consume first colon */
1660 while (*vp
->ptr
!= '\0') {
1661 char *newStr
; /* New value to return */
1663 if (*vp
->ptr
== endc
) {
1667 DEBUGF(VAR
, ("Applying :%c to \"%s\"\n", *vp
->ptr
, value
));
1671 newStr
= modifier_M(vp
, value
, endc
);
1674 newStr
= modifier_S(vp
, value
, v
);
1677 newStr
= modifier_C(vp
, value
, v
);
1680 if (vp
->ptr
[1] != endc
&& vp
->ptr
[1] != ':') {
1682 if ((vp
->ptr
[0] == 's') &&
1683 (vp
->ptr
[1] == 'h') &&
1684 (vp
->ptr
[2] == endc
|| vp
->ptr
[2] == ':')) {
1689 Cmd_Exec(value
, &error
));
1691 newStr
= estrdup("");
1695 Error(error
, value
);
1700 newStr
= sysVvarsub(vp
, startc
, v
, value
);
1705 switch (vp
->ptr
[0]) {
1710 buf
= Buf_Init(MAKE_BSIZE
);
1711 for (cp
= value
; *cp
; cp
++)
1712 Buf_AddByte(buf
, tolower((unsigned char)*cp
));
1714 newStr
= Buf_Peel(buf
);
1720 newStr
= VarSortWords(value
, SortIncreasing
);
1724 newStr
= Var_Quote(value
);
1728 newStr
= VarModify(value
, VarTail
, NULL
);
1735 buf
= Buf_Init(MAKE_BSIZE
);
1736 for (cp
= value
; *cp
; cp
++)
1737 Buf_AddByte(buf
, toupper((unsigned char)*cp
));
1739 newStr
= Buf_Peel(buf
);
1745 newStr
= VarModify(value
, VarHead
, NULL
);
1749 newStr
= VarModify(value
, VarSuffix
, NULL
);
1753 newStr
= VarModify(value
, VarRoot
, NULL
);
1757 newStr
= sysVvarsub(vp
, startc
, v
, value
);
1763 DEBUGF(VAR
, ("Result is \"%s\"\n", newStr
));
1769 *freeResult
= (value
== var_Error
) ? false : true;
1771 if (vp
->ptr
[0] == ':') {
1772 vp
->ptr
++; /* consume colon */
1780 ParseRestModifier(VarParser
*vp
, char startc
, Buffer
*buf
, bool *freeResult
)
1787 vname
= Buf_Data(buf
);
1788 vlen
= Buf_Size(buf
);
1790 v
= VarFindAny(vname
, vp
->ctxt
);
1792 value
= ParseModifier(vp
, startc
, v
, freeResult
);
1796 if ((vp
->ctxt
== VAR_CMD
) || (vp
->ctxt
== VAR_GLOBAL
)) {
1799 * Still need to get to the end of the variable
1800 * specification, so kludge up a Var structure for the
1803 v
= VarCreate(vname
, NULL
, VAR_JUNK
);
1804 value
= ParseModifier(vp
, startc
, v
, freeResult
);
1808 VarDestroy(v
, true);
1810 consumed
= vp
->ptr
- vp
->input
+ 1;
1812 * If substituting a local variable in a non-local context,
1813 * assume it's for dynamic source stuff. We have to handle
1814 * this specially and return the longhand for the variable
1815 * with the dollar sign escaped so it makes it back to the
1816 * caller. Only four of the local variables are treated
1817 * specially as they are the only four that will be set when
1818 * dynamic sources are expanded.
1821 (vlen
== 2 && (vname
[1] == 'F' || vname
[1] == 'D'))) {
1822 if (strchr("!%*@", vname
[0]) != NULL
) {
1823 value
= emalloc(consumed
+ 1);
1824 strncpy(value
, vp
->input
, consumed
);
1825 value
[consumed
] = '\0';
1833 isupper((unsigned char)vname
[1])) {
1834 if ((strncmp(vname
, ".TARGET", vlen
- 1) == 0) ||
1835 (strncmp(vname
, ".ARCHIVE", vlen
- 1) == 0) ||
1836 (strncmp(vname
, ".PREFIX", vlen
- 1) == 0) ||
1837 (strncmp(vname
, ".MEMBER", vlen
- 1) == 0)) {
1838 value
= emalloc(consumed
+ 1);
1839 strncpy(value
, vp
->input
, consumed
);
1840 value
[consumed
] = '\0';
1847 *freeResult
= false;
1848 return (vp
->err
? var_Error
: varNoError
);
1851 * Check for D and F forms of local variables since we're in
1852 * a local context and the name is the right length.
1855 (vname
[1] == 'F' || vname
[1] == 'D') &&
1856 (strchr("!%*<>@", vname
[0]) != NULL
)) {
1862 v
= VarFindOnly(name
, vp
->ctxt
);
1864 value
= ParseModifier(vp
, startc
, v
, freeResult
);
1870 * Still need to get to the end of the variable
1871 * specification, so kludge up a Var structure for the
1874 v
= VarCreate(vname
, NULL
, VAR_JUNK
);
1875 value
= ParseModifier(vp
, startc
, v
, freeResult
);
1879 VarDestroy(v
, true);
1881 *freeResult
= false;
1882 return (vp
->err
? var_Error
: varNoError
);
1887 ParseRestEnd(VarParser
*vp
, Buffer
*buf
, bool *freeResult
)
1894 vname
= Buf_Data(buf
);
1895 vlen
= Buf_Size(buf
);
1897 v
= VarFindAny(vname
, vp
->ctxt
);
1899 value
= VarExpand(v
, vp
);
1904 if ((vp
->ctxt
== VAR_CMD
) || (vp
->ctxt
== VAR_GLOBAL
)) {
1905 size_t consumed
= vp
->ptr
- vp
->input
+ 1;
1908 * If substituting a local variable in a non-local context,
1909 * assume it's for dynamic source stuff. We have to handle
1910 * this specially and return the longhand for the variable
1911 * with the dollar sign escaped so it makes it back to the
1912 * caller. Only four of the local variables are treated
1913 * specially as they are the only four that will be set when
1914 * dynamic sources are expanded.
1917 (vlen
== 2 && (vname
[1] == 'F' || vname
[1] == 'D'))) {
1918 if (strchr("!%*@", vname
[0]) != NULL
) {
1919 value
= emalloc(consumed
+ 1);
1920 strncpy(value
, vp
->input
, consumed
);
1921 value
[consumed
] = '\0';
1929 isupper((unsigned char)vname
[1])) {
1930 if ((strncmp(vname
, ".TARGET", vlen
- 1) == 0) ||
1931 (strncmp(vname
, ".ARCHIVE", vlen
- 1) == 0) ||
1932 (strncmp(vname
, ".PREFIX", vlen
- 1) == 0) ||
1933 (strncmp(vname
, ".MEMBER", vlen
- 1) == 0)) {
1934 value
= emalloc(consumed
+ 1);
1935 strncpy(value
, vp
->input
, consumed
);
1936 value
[consumed
] = '\0';
1944 * Check for D and F forms of local variables since we're in
1945 * a local context and the name is the right length.
1948 (vname
[1] == 'F' || vname
[1] == 'D') &&
1949 (strchr("!%*<>@", vname
[0]) != NULL
)) {
1955 v
= VarFindOnly(name
, vp
->ctxt
);
1959 * No need for nested expansion or anything,
1960 * as we're the only one who sets these
1961 * things and we sure don't put nested
1962 * invocations in them...
1964 val
= Buf_Data(v
->val
);
1966 if (vname
[1] == 'D') {
1967 val
= VarModify(val
, VarHead
, NULL
);
1969 val
= VarModify(val
, VarTail
, NULL
);
1978 *freeResult
= false;
1979 return (vp
->err
? var_Error
: varNoError
);
1983 * Parse a multi letter variable name, and return it's value.
1986 VarParseLong(VarParser
*vp
, bool *freeResult
)
1993 buf
= Buf_Init(MAKE_BSIZE
);
1995 startc
= vp
->ptr
[0];
1996 vp
->ptr
++; /* consume opening paren or brace */
1998 endc
= (startc
== OPEN_PAREN
) ? CLOSE_PAREN
: CLOSE_BRACE
;
2001 * Process characters until we reach an end character or a colon,
2002 * replacing embedded variables as we go.
2004 while (*vp
->ptr
!= '\0') {
2005 if (*vp
->ptr
== endc
) {
2006 value
= ParseRestEnd(vp
, buf
, freeResult
);
2007 vp
->ptr
++; /* consume closing paren or brace */
2008 Buf_Destroy(buf
, true);
2011 } else if (*vp
->ptr
== ':') {
2012 value
= ParseRestModifier(vp
, startc
, buf
, freeResult
);
2013 vp
->ptr
++; /* consume closing paren or brace */
2014 Buf_Destroy(buf
, true);
2017 } else if (*vp
->ptr
== '$') {
2028 rval
= VarParse(&subvp
, &rfree
);
2029 if (rval
== var_Error
) {
2030 Fatal("Error expanding embedded variable.");
2032 Buf_Append(buf
, rval
);
2035 vp
->ptr
= subvp
.ptr
;
2037 Buf_AddByte(buf
, *vp
->ptr
);
2042 /* If we did not find the end character, return var_Error */
2043 Buf_Destroy(buf
, true);
2044 *freeResult
= false;
2049 * Parse a single letter variable name, and return it's value.
2052 VarParseShort(VarParser
*vp
, bool *freeResult
)
2058 vname
[0] = vp
->ptr
[0];
2061 vp
->ptr
++; /* consume single letter */
2063 v
= VarFindAny(vname
, vp
->ctxt
);
2065 value
= VarExpand(v
, vp
);
2071 * If substituting a local variable in a non-local context, assume
2072 * it's for dynamic source stuff. We have to handle this specially
2073 * and return the longhand for the variable with the dollar sign
2074 * escaped so it makes it back to the caller. Only four of the local
2075 * variables are treated specially as they are the only four that
2076 * will be set when dynamic sources are expanded.
2078 if ((vp
->ctxt
== VAR_CMD
) || (vp
->ctxt
== VAR_GLOBAL
)) {
2080 /* XXX: It looks like $% and $! are reversed here */
2084 return (estrdup("$(.TARGET)"));
2087 return (estrdup("$(.ARCHIVE)"));
2090 return (estrdup("$(.PREFIX)"));
2093 return (estrdup("$(.MEMBER)"));
2095 *freeResult
= false;
2096 return (vp
->err
? var_Error
: varNoError
);
2100 /* Variable name was not found. */
2101 *freeResult
= false;
2102 return (vp
->err
? var_Error
: varNoError
);
2106 VarParse(VarParser
*vp
, bool *freeResult
)
2109 vp
->ptr
++; /* consume '$' or last letter of conditional */
2111 if (vp
->ptr
[0] == '\0') {
2112 /* Error, there is only a dollar sign in the input string. */
2113 *freeResult
= false;
2114 return (vp
->err
? var_Error
: varNoError
);
2116 } else if (vp
->ptr
[0] == OPEN_PAREN
|| vp
->ptr
[0] == OPEN_BRACE
) {
2117 /* multi letter variable name */
2118 return (VarParseLong(vp
, freeResult
));
2121 /* single letter variable name */
2122 return (VarParseShort(vp
, freeResult
));
2127 * Given the start of a variable invocation, extract the variable
2128 * name and find its value, then modify it according to the
2132 * The value of the variable or var_Error if the specification
2133 * is invalid. The number of characters in the specification
2134 * is placed in the variable pointed to by consumed. (for
2135 * invalid specifications, this is just 2 to skip the '$' and
2136 * the following letter, or 1 if '$' was the last character
2137 * in the string). A bool in *freeResult telling whether the
2138 * returned string should be freed by the caller.
2141 Var_Parse(const char input
[], GNode
*ctxt
, bool err
,
2142 size_t *consumed
, bool *freeResult
)
2153 value
= VarParse(&vp
, freeResult
);
2154 *consumed
+= vp
.ptr
- vp
.input
;
2159 * Given the start of a variable invocation, determine the length
2160 * of the specification.
2163 * The number of characters in the specification. For invalid
2164 * specifications, this is just 2 to skip the '$' and the
2165 * following letter, or 1 if '$' was the last character in the
2169 Var_Match(const char input
[], GNode
*ctxt
)
2181 value
= VarParse(&vp
, &freeResult
);
2185 return (vp
.ptr
- vp
.input
);
2189 match_var(const char str
[], const char var
[])
2191 const char *start
= str
;
2194 str
++; /* consume '$' */
2196 if (str
[0] == OPEN_PAREN
|| str
[0] == OPEN_BRACE
) {
2197 str
++; /* consume opening paren or brace */
2199 while (str
[0] != '\0') {
2200 if (str
[0] == '$') {
2202 * A variable inside the variable. We cannot
2203 * expand the external variable yet.
2205 return (str
- start
);
2206 } else if (str
[0] == ':' ||
2207 str
[0] == CLOSE_PAREN
||
2208 str
[0] == CLOSE_BRACE
) {
2209 len
= str
- (start
+ 2);
2211 if (var
[len
] == '\0' && strncmp(var
, start
+ 2, len
) == 0) {
2212 return (0); /* match */
2215 * Not the variable we want to
2218 return (str
- start
);
2224 return (str
- start
);
2226 /* Single letter variable name */
2227 if (var
[1] == '\0' && var
[0] == str
[0]) {
2228 return (0); /* match */
2230 str
++; /* consume variable name */
2231 return (str
- start
);
2237 * Substitute for all variables in the given string in the given
2238 * context If err is true, Parse_Error will be called when an
2239 * undefined variable is encountered.
2242 * The resulting string.
2245 * None. The old string must be freed by the caller
2248 Var_Subst(const char str
[], GNode
*ctxt
, bool err
)
2251 Buffer
*buf
; /* Buffer for forming things */
2254 * Set true if an error has already been reported to prevent a
2255 * plethora of messages when recursing. XXXHB this comment sounds
2258 errorReported
= false;
2261 while (str
[0] != '\0') {
2262 if ((str
[0] == '$') && (str
[1] == '$')) {
2264 * A dollar sign may be escaped with another dollar
2265 * sign. In such a case, we skip over the escape
2266 * character and store the dollar sign into the
2270 Buf_AddByte(buf
, str
[0]);
2273 } else if (str
[0] == '$') {
2274 /* Variable invocation. */
2285 rval
= VarParse(&subvp
, &rfree
);
2288 * When we come down here, val should either point to
2289 * the value of this variable, suitably modified, or
2290 * be NULL. Length should be the total length of the
2291 * potential variable invocation (from $ to end
2294 if (rval
== var_Error
|| rval
== varNoError
) {
2296 * If performing old-time variable
2297 * substitution, skip over the variable and
2298 * continue with the substitution. Otherwise,
2299 * store the dollar sign and advance str so
2300 * we continue with the string...
2306 * If variable is undefined, complain
2307 * and skip the variable. The
2308 * complaint will stop us from doing
2309 * anything when the file is parsed.
2311 if (!errorReported
) {
2312 Parse_Error(PARSE_FATAL
,
2313 "Undefined variable \"%.*s\"", subvp
.ptr
- subvp
.input
, str
);
2315 errorReported
= true;
2318 Buf_AddByte(buf
, str
[0]);
2323 * Copy all the characters from the variable
2324 * value straight into the new string.
2326 Buf_Append(buf
, rval
);
2333 Buf_AddByte(buf
, str
[0]);
2342 * Substitute for all variables except if it is the same as 'var',
2343 * in the given string in the given context. If err is true,
2344 * Parse_Error will be called when an undefined variable is
2348 * The resulting string.
2351 * None. The old string must be freed by the caller
2354 Var_SubstOnly(const char var
[], const char str
[], bool err
)
2356 GNode
*ctxt
= VAR_GLOBAL
;
2358 Buffer
*buf
; /* Buffer for forming things */
2361 * Set true if an error has already been reported to prevent a
2362 * plethora of messages when recursing. XXXHB this comment sounds
2365 errorReported
= false;
2368 while (str
[0] != '\0') {
2369 if (str
[0] == '$') {
2372 skip
= match_var(str
, var
);
2374 Buf_AddBytes(buf
, skip
, str
);
2377 /* Variable invocation. */
2388 rval
= VarParse(&subvp
, &rfree
);
2391 * When we get down here, rval should either
2392 * point to the value of this variable, or be
2395 if (rval
== var_Error
|| rval
== varNoError
) {
2397 * If performing old-time variable
2398 * substitution, skip over the
2399 * variable and continue with the
2400 * substitution. Otherwise, store the
2401 * dollar sign and advance str so we
2402 * continue with the string...
2408 * If variable is undefined,
2409 * complain and skip the
2410 * variable. The complaint
2411 * will stop us from doing
2412 * anything when the file is
2415 if (!errorReported
) {
2416 Parse_Error(PARSE_FATAL
,
2417 "Undefined variable \"%.*s\"", subvp
.ptr
- subvp
.input
, str
);
2419 errorReported
= true;
2422 Buf_AddByte(buf
, str
[0]);
2427 * Copy all the characters from the
2428 * variable value straight into the
2431 Buf_Append(buf
, rval
);
2439 Buf_AddByte(buf
, str
[0]);
2448 * Initialize the module
2451 * The VAR_CMD and VAR_GLOBAL contexts are created
2454 Var_Init(char **env
)
2458 VAR_CMD
= Targ_NewGN("Command");
2459 VAR_ENV
= Targ_NewGN("Environment");
2460 VAR_GLOBAL
= Targ_NewGN("Global");
2463 * Copy user environment variables into ENV context.
2465 for (ptr
= env
; *ptr
!= NULL
; ++ptr
) {
2466 char *tmp
= estrdup(*ptr
);
2467 const char *name
= tmp
;
2468 char *sep
= strchr(name
, '=');
2471 const char *value
= sep
+ 1;
2474 VarAdd(name
, value
, VAR_ENV
);
2481 * Print all variables in global and command line contexts.
2489 printf("#*** Global Variables:\n");
2490 LST_FOREACH(ln
, &VAR_GLOBAL
->context
) {
2492 printf("%-16s = %s\n", v
->name
, Buf_Data(v
->val
));
2495 printf("#*** Command-line Variables:\n");
2496 LST_FOREACH(ln
, &VAR_CMD
->context
) {
2498 printf("%-16s = %s\n", v
->name
, Buf_Data(v
->val
));
2503 * Print the values of any variables requested by
2507 Var_Print(Lst
*vlist
, bool expandVars
)
2511 LST_FOREACH(n
, vlist
) {
2512 const char *name
= Lst_Datum(n
);
2518 v
= emalloc(strlen(name
) + 1 + 3);
2519 sprintf(v
, "${%s}", name
);
2521 value
= Buf_Peel(Var_Subst(v
, VAR_GLOBAL
, false));
2522 printf("%s\n", value
);
2527 const char *value
= Var_Value(name
, VAR_GLOBAL
);
2528 printf("%s\n", value
!= NULL
? value
: "");