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
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
47 * Variable-handling functions
50 * Var_Set Set the value of a variable in the given
51 * context. The variable is created if it doesn't
52 * yet exist. The value and variable name need not
55 * Var_Append Append more characters to an existing variable
56 * in the given context. The variable needn't
57 * exist already -- it will be created if it doesn't.
58 * A space is placed between the old value and the
61 * Var_Exists See if a variable exists.
63 * Var_Value Return the value of a variable in a context or
64 * NULL if the variable is undefined.
66 * Var_Subst Substitute named variable, or all variables if
67 * NULL in a string using
68 * the given context as the top-most one. If the
69 * third argument is non-zero, Parse_Error is
70 * called if any variables are undefined.
72 * Var_Parse Parse a variable expansion from a string and
73 * return the result and the number of characters
76 * Var_Delete Delete a variable in a context.
78 * Var_Init Initialize this module.
81 * Var_Dump Print out all variables defined in the given
84 * XXX: There's a lot of duplication in these functions.
90 #include <sys/types.h>
108 typedef struct VarParser {
109 const char *const input; /* pointer to input string */
110 const char *ptr; /* current parser pos in input str */
117 char *name; /* the variable's name */
118 struct Buffer *val; /* its value */
119 int flags; /* miscellaneous status flags */
121 #define VAR_IN_USE 1 /* Variable's value currently being used.
122 * Used to avoid recursion */
124 #define VAR_JUNK 4 /* Variable is a junk variable that
125 * should be destroyed when done with
126 * it. Used by Var_Parse for undefined,
127 * modified variables */
129 #define VAR_TO_ENV 8 /* Place variable in environment */
133 struct Buffer *lhs; /* String to match */
134 struct Buffer *rhs; /* Replacement string (w/ &'s removed) */
141 #define VAR_SUB_GLOBAL 0x01 /* Apply substitution globally */
142 #define VAR_SUB_ONE 0x02 /* Apply substitution to one word */
143 #define VAR_SUB_MATCHED 0x04 /* There was a match */
144 #define VAR_MATCH_START 0x08 /* Match at start of word */
145 #define VAR_MATCH_END 0x10 /* Match at end of word */
148 typedef Boolean VarModifyProc(const char *, Boolean, struct Buffer *, void *);
150 static char *VarParse(VarParser *, Boolean *);
153 * This is a harmless return value for Var_Parse that can be used by Var_Subst
154 * to determine if there was an error in parsing -- easier than returning
155 * a flag, as things outside this module don't give a hoot.
157 char var_Error[] = "";
160 * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
161 * set false. Why not just use a constant? Well, gcc likes to condense
162 * identical string instances...
164 static char varNoError[] = "";
167 * Internally, variables are contained in four different contexts.
168 * 1) the environment. They may not be changed. If an environment
169 * variable is appended-to, the result is placed in the global
171 * 2) the global context. Variables set in the Makefile are located in
172 * the global context. It is the penultimate context searched when
174 * 3) the command-line context. All variables set on the command line
175 * are placed in this context. They are UNALTERABLE once placed here.
176 * 4) the local context. Each target has associated with it a context
177 * list. On this list are located the structures describing such
178 * local variables as $(@) and $(*)
179 * The four contexts are searched in the reverse order from which they are
182 static GNode *VAR_ENV; /* variables from the environment */
183 GNode *VAR_GLOBAL; /* variables from the makefile */
184 GNode *VAR_CMD; /* variables defined on the command-line */
186 Boolean oldVars; /* variable substitution style */
187 Boolean checkEnvFirst; /* -e flag */
189 #define OPEN_PAREN '('
190 #define CLOSE_PAREN ')'
191 #define OPEN_BRACE '{'
192 #define CLOSE_BRACE '}'
195 * Create a Var object.
198 * name Name of variable (copied).
199 * value Value of variable (copied) or NULL.
200 * flags Flags set on variable.
206 VarCreate(const char name[], const char value[], int flags)
210 v = emalloc(sizeof(Var));
211 v->name = estrdup(name);
212 v->val = Buf_Init(0);
216 Buf_Append(v->val, value);
222 * Destroy a Var object.
225 * v Object to destroy.
226 * f True if internal buffer in Buffer object is to be removed.
229 VarDestroy(Var *v, Boolean f)
232 Buf_Destroy(v->val, f);
238 * Remove the tail of the given word and place the result in the given
242 * TRUE if characters were added to the buffer (a space needs to be
243 * added to the buffer before the next word).
246 * The trimmed word is added to the buffer.
249 VarHead(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
253 slash = strrchr(word, '/');
256 Buf_AddByte(buf, (Byte)' ');
258 Buf_AppendRange(buf, word, slash);
261 * If no directory part, give . (q.v. the POSIX standard)
264 Buf_Append(buf, " .");
266 Buf_AddByte(buf, (Byte)'.');
273 * Remove the head of the given word and place the result in the given
277 * TRUE if characters were added to the buffer (a space needs to be
278 * added to the buffer before the next word).
281 * The trimmed word is added to the buffer.
284 VarTail(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
289 Buf_AddByte (buf, (Byte)' ');
292 slash = strrchr(word, '/');
295 Buf_Append(buf, slash);
297 Buf_Append(buf, word);
303 * Place the suffix of the given word in the given buffer.
306 * TRUE if characters were added to the buffer (a space needs to be
307 * added to the buffer before the next word).
310 * The suffix from the word is placed in the buffer.
313 VarSuffix(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
317 dot = strrchr(word, '.');
320 Buf_AddByte(buf, (Byte)' ');
323 Buf_Append(buf, dot);
330 * Remove the suffix of the given word and place the result in the
334 * TRUE if characters were added to the buffer (a space needs to be
335 * added to the buffer before the next word).
338 * The trimmed word is added to the buffer.
341 VarRoot(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
346 Buf_AddByte(buf, (Byte)' ');
349 dot = strrchr(word, '.');
351 Buf_AppendRange(buf, word, dot);
353 Buf_Append(buf, word);
359 * Place the word in the buffer if it matches the given pattern.
360 * Callback function for VarModify to implement the :M modifier.
361 * A space will be added if requested. A pattern is supplied
362 * which the word must match.
365 * TRUE if a space should be placed in the buffer before the next
369 * The word may be copied to the buffer.
372 VarMatch(const char *word, Boolean addSpace, Buffer *buf, void *pattern)
375 if (Str_Match(word, pattern)) {
377 Buf_AddByte(buf, (Byte)' ');
380 Buf_Append(buf, word);
387 * Place the word in the buffer if it matches the given pattern.
388 * Callback function for VarModify to implement the System V %
389 * modifiers. A space is added if requested.
392 * TRUE if a space should be placed in the buffer before the next
396 * The word may be copied to the buffer.
399 VarSYSVMatch(const char *word, Boolean addSpace, Buffer *buf, void *patp)
403 VarPattern *pat = (VarPattern *)patp;
406 Buf_AddByte(buf, (Byte)' ');
410 if ((ptr = Str_SYSVMatch(word, Buf_Data(pat->lhs), &len)) != NULL)
411 Str_SYSVSubst(buf, Buf_Data(pat->rhs), ptr, len);
413 Buf_Append(buf, word);
420 * Place the word in the buffer if it doesn't match the given pattern.
421 * Callback function for VarModify to implement the :N modifier. A
422 * space is added if requested.
425 * TRUE if a space should be placed in the buffer before the next
429 * The word may be copied to the buffer.
432 VarNoMatch(const char *word, Boolean addSpace, Buffer *buf, void *pattern)
435 if (!Str_Match(word, pattern)) {
437 Buf_AddByte(buf, (Byte)' ');
440 Buf_Append(buf, word);
446 * Perform a string-substitution on the given word, placing the
447 * result in the passed buffer. A space is added if requested.
450 * TRUE if a space is needed before more characters are added.
453 VarSubstitute(const char *word, Boolean addSpace, Buffer *buf, void *patternp)
455 size_t wordLen; /* Length of word */
456 const char *cp; /* General pointer */
457 VarPattern *pattern = patternp;
459 wordLen = strlen(word);
460 if (1) { /* substitute in each word of the variable */
462 * Break substitution down into simple anchored cases
463 * and if none of them fits, perform the general substitution
466 if ((pattern->flags & VAR_MATCH_START) &&
467 (strncmp(word, Buf_Data(pattern->lhs),
468 Buf_Size(pattern->lhs)) == 0)) {
470 * Anchored at start and beginning of word matches
473 if ((pattern->flags & VAR_MATCH_END) &&
474 (wordLen == Buf_Size(pattern->lhs))) {
476 * Also anchored at end and matches to the end
477 * (word is same length as pattern) add space
478 * and rhs only if rhs is non-null.
480 if (Buf_Size(pattern->rhs) != 0) {
482 Buf_AddByte(buf, (Byte)' ');
485 Buf_AppendBuf(buf, pattern->rhs);
488 } else if (pattern->flags & VAR_MATCH_END) {
490 * Doesn't match to end -- copy word wholesale
496 * Matches at start but need to copy in
497 * trailing characters.
499 if ((Buf_Size(pattern->rhs) + wordLen -
500 Buf_Size(pattern->lhs)) != 0) {
502 Buf_AddByte(buf, (Byte)' ');
506 Buf_AppendBuf(buf, pattern->rhs);
507 Buf_AddBytes(buf, wordLen -
508 Buf_Size(pattern->lhs),
509 (word + Buf_Size(pattern->lhs)));
512 } else if (pattern->flags & VAR_MATCH_START) {
514 * Had to match at start of word and didn't -- copy
519 } else if (pattern->flags & VAR_MATCH_END) {
521 * Anchored at end, Find only place match could occur
522 * (leftLen characters from the end of the word) and
523 * see if it does. Note that because the $ will be
524 * left at the end of the lhs, we have to use strncmp.
526 cp = word + (wordLen - Buf_Size(pattern->lhs));
527 if ((cp >= word) && (strncmp(cp, Buf_Data(pattern->lhs),
528 Buf_Size(pattern->lhs)) == 0)) {
530 * Match found. If we will place characters in
531 * the buffer, add a space before hand as
532 * indicated by addSpace, then stuff in the
533 * initial, unmatched part of the word followed
534 * by the right-hand-side.
536 if ((cp - word) + Buf_Size(pattern->rhs) != 0) {
538 Buf_AddByte(buf, (Byte)' ');
542 Buf_AppendRange(buf, word, cp);
543 Buf_AppendBuf(buf, pattern->rhs);
547 * Had to match at end and didn't. Copy entire
554 * Pattern is unanchored: search for the pattern in the
555 * word using strstr(3), copying unmatched portions and
556 * the right-hand-side for each match found, handling
557 * non-global substitutions correctly, etc. When the
558 * loop is done, any remaining part of the word (word
559 * and wordLen are adjusted accordingly through the
560 * loop) is copied straight into the buffer.
561 * addSpace is set FALSE as soon as a space is added
568 origSize = Buf_Size(buf);
570 cp = strstr(word, Buf_Data(pattern->lhs));
572 if (addSpace && (((cp - word) +
573 Buf_Size(pattern->rhs)) != 0)) {
574 Buf_AddByte(buf, (Byte)' ');
577 Buf_AppendRange(buf, word, cp);
578 Buf_AppendBuf(buf, pattern->rhs);
579 wordLen -= (cp - word) +
580 Buf_Size(pattern->lhs);
581 word = cp + Buf_Size(pattern->lhs);
582 if (wordLen == 0 || (pattern->flags &
583 VAR_SUB_GLOBAL) == 0) {
592 Buf_AddByte(buf, (Byte)' ');
594 Buf_AddBytes(buf, wordLen, (const Byte *)word);
598 * If added characters to the buffer, need to add a
599 * space before we add any more. If we didn't add any,
600 * just return the previous value of addSpace.
602 return ((Buf_Size(buf) != origSize) || addSpace);
605 * Common code for anchored substitutions:
606 * addSpace was set TRUE if characters were added to the buffer.
612 Buf_AddByte(buf, (Byte)' ');
614 Buf_AddBytes(buf, wordLen, (const Byte *)word);
619 * Print the error caused by a regcomp or regexec call.
622 * An error gets printed.
625 VarREError(int err, regex_t *pat, const char *str)
630 errlen = regerror(err, pat, 0, 0);
631 errbuf = emalloc(errlen);
632 regerror(err, pat, errbuf, errlen);
633 Error("%s: %s", str, errbuf);
639 * Perform a regex substitution on the given word, placing the
640 * result in the passed buffer. A space is added if requested.
643 * TRUE if a space is needed before more characters are added.
646 VarRESubstitute(const char *word, Boolean addSpace, Buffer *buf, void *patternp)
655 #define MAYBE_ADD_SPACE() \
656 if (addSpace && !added) \
657 Buf_AddByte(buf, (Byte)' '); \
664 if ((pat->flags & (VAR_SUB_ONE | VAR_SUB_MATCHED)) ==
665 (VAR_SUB_ONE | VAR_SUB_MATCHED)) {
669 xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
674 pat->flags |= VAR_SUB_MATCHED;
675 if (pat->matches[0].rm_so > 0) {
677 Buf_AddBytes(buf, pat->matches[0].rm_so,
681 for (rp = Buf_Data(pat->rhs); *rp; rp++) {
682 if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
684 Buf_AddByte(buf, (Byte)rp[1]);
687 } else if ((*rp == '&') ||
688 ((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
707 Error("No subexpression %s",
712 } else if ((pat->matches[n].rm_so == -1) &&
713 (pat->matches[n].rm_eo == -1)) {
714 Error("No match for subexpression %s",
720 subbuf = wp + pat->matches[n].rm_so;
721 sublen = pat->matches[n].rm_eo -
722 pat->matches[n].rm_so;
727 Buf_AddBytes(buf, sublen,
728 (const Byte *)subbuf);
732 Buf_AddByte(buf, (Byte)*rp);
735 wp += pat->matches[0].rm_eo;
736 if (pat->flags & VAR_SUB_GLOBAL) {
738 if (pat->matches[0].rm_so == 0 &&
739 pat->matches[0].rm_eo == 0) {
741 Buf_AddByte(buf, (Byte)*wp);
754 VarREError(xrv, &pat->re, "Unexpected regex error");
764 return (addSpace || added);
768 * Find a variable in a variable list.
771 VarLookup(Lst *vlist, const char *name)
775 LST_FOREACH(ln, vlist)
776 if (strcmp(((const Var *)Lst_Datum(ln))->name, name) == 0)
777 return (Lst_Datum(ln));
782 * Expand a variable name's embedded variables in the given context.
785 * The contents of name, possibly expanded.
788 VarPossiblyExpand(const char *name, GNode *ctxt)
792 if (strchr(name, '$') != NULL) {
793 buf = Var_Subst(name, ctxt, 0);
794 return (Buf_Peel(buf));
796 return estrdup(name);
801 * If the variable name begins with a '.', it could very well be
802 * one of the local ones. We check the name against all the local
803 * variables and substitute the short version in for 'name' if it
804 * matches one of them.
807 VarLocal(const char name[])
809 if (name[0] == '.') {
812 if (!strcmp(name, ".ALLSRC"))
814 if (!strcmp(name, ".ARCHIVE"))
818 if (!strcmp(name, ".IMPSRC"))
822 if (!strcmp(name, ".MEMBER"))
826 if (!strcmp(name, ".OODATE"))
830 if (!strcmp(name, ".PREFIX"))
834 if (!strcmp(name, ".TARGET"))
845 * Find the given variable in the given context and the environment.
848 * A pointer to the structure describing the desired variable or
849 * NULL if the variable does not exist.
852 VarFindEnv(const char name[], GNode *ctxt)
856 name = VarLocal(name);
858 if ((var = VarLookup(&ctxt->context, name)) != NULL)
861 if ((var = VarLookup(&VAR_ENV->context, name)) != NULL)
868 * Look for the variable in the given context.
871 VarFindOnly(const char name[], GNode *ctxt)
875 name = VarLocal(name);
877 if ((var = VarLookup(&ctxt->context, name)) != NULL)
884 * Look for the variable in all contexts.
887 VarFindAny(const char name[], GNode *ctxt)
889 Boolean localCheckEnvFirst;
893 name = VarLocal(name);
896 * Note whether this is one of the specific variables we were told
897 * through the -E flag to use environment-variable-override for.
899 localCheckEnvFirst = FALSE;
900 LST_FOREACH(ln, &envFirstVars) {
901 if (strcmp(Lst_Datum(ln), name) == 0) {
902 localCheckEnvFirst = TRUE;
908 * First look for the variable in the given context. If it's not there,
909 * look for it in VAR_CMD, VAR_GLOBAL and the environment,
910 * in that order, depending on the FIND_* flags in 'flags'
912 if ((var = VarLookup(&ctxt->context, name)) != NULL)
915 /* not there - try command line context */
916 if (ctxt != VAR_CMD) {
917 if ((var = VarLookup(&VAR_CMD->context, name)) != NULL)
921 /* not there - try global context, but only if not -e/-E */
922 if (ctxt != VAR_GLOBAL && (!checkEnvFirst && !localCheckEnvFirst)) {
923 if ((var = VarLookup(&VAR_GLOBAL->context, name)) != NULL)
927 if ((var = VarLookup(&VAR_ENV->context, name)) != NULL)
930 /* deferred check for the environment (in case of -e/-E) */
931 if ((ctxt != VAR_GLOBAL) && (checkEnvFirst || localCheckEnvFirst)) {
932 if ((var = VarLookup(&VAR_GLOBAL->context, name)) != NULL)
940 * Add a new variable of name name and value val to the given context.
943 * The new variable is placed at the front of the given context
944 * The name and val arguments are duplicated so they may
948 VarAdd(const char *name, const char *val, GNode *ctxt)
952 Lst_AtFront(&ctxt->context, v = VarCreate(name, val, 0));
953 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
958 * Remove a variable from a context.
961 * The Var structure is removed and freed.
964 Var_Delete(const char *name, GNode *ctxt)
968 DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
969 LST_FOREACH(ln, &ctxt->context) {
970 if (strcmp(((const Var *)Lst_Datum(ln))->name, name) == 0) {
971 VarDestroy(Lst_Datum(ln), TRUE);
972 Lst_Remove(&ctxt->context, ln);
979 * Set the variable name to the value val in the given context.
982 * If the variable doesn't yet exist, a new record is created for it.
983 * Else the old value is freed and the new one stuck in its place
986 * The variable is searched for only in its context before being
987 * created in that context. I.e. if the context is VAR_GLOBAL,
988 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
989 * VAR_CMD->context is searched. This is done to avoid the literally
990 * thousands of unnecessary strcmp's that used to be done to
991 * set, say, $(@) or $(<).
994 Var_Set(const char *name, const char *val, GNode *ctxt)
1000 * We only look for a variable in the given context since anything
1001 * set here will override anything in a lower context, so there's not
1002 * much point in searching them all just to save a bit of memory...
1004 n = VarPossiblyExpand(name, ctxt);
1005 v = VarFindOnly(n, ctxt);
1007 v = VarAdd(n, val, ctxt);
1010 Buf_Append(v->val, val);
1011 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, val));
1014 if (ctxt == VAR_CMD || (v->flags & VAR_TO_ENV)) {
1016 * Any variables given on the command line
1017 * are automatically exported to the
1018 * environment (as per POSIX standard)
1027 * Set the a global name variable to the value.
1030 Var_SetGlobal(const char name[], const char value[])
1033 Var_Set(name, value, VAR_GLOBAL);
1038 * Set the VAR_TO_ENV flag on a variable
1041 Var_SetEnv(const char *name, GNode *ctxt)
1045 v = VarFindOnly(name, VAR_CMD);
1048 * Do not allow .EXPORT: to be set on variables
1049 * from the comand line or MAKEFLAGS.
1052 "Warning: Did not set .EXPORTVAR: on %s because it "
1053 "is from the comand line or MAKEFLAGS", name);
1057 v = VarFindAny(name, ctxt);
1059 Lst_AtFront(&VAR_ENV->context,
1060 VarCreate(name, NULL, VAR_TO_ENV));
1061 setenv(name, "", 1);
1062 Error("Warning: .EXPORTVAR: set on undefined variable %s", name);
1064 if ((v->flags & VAR_TO_ENV) == 0) {
1065 v->flags |= VAR_TO_ENV;
1066 setenv(v->name, Buf_Data(v->val), 1);
1072 * The variable of the given name has the given value appended to it in
1073 * the given context.
1076 * If the variable doesn't exist, it is created. Else the strings
1077 * are concatenated (with a space in between).
1080 * Only if the variable is being sought in the global context is the
1081 * environment searched.
1082 * XXX: Knows its calling circumstances in that if called with ctxt
1083 * an actual target, it will only search that context since only
1084 * a local variable could be being appended to. This is actually
1085 * a big win and must be tolerated.
1088 Var_Append(const char *name, const char *val, GNode *ctxt)
1093 n = VarPossiblyExpand(name, ctxt);
1094 if (ctxt == VAR_GLOBAL) {
1095 v = VarFindEnv(n, ctxt);
1097 v = VarFindOnly(n, ctxt);
1100 VarAdd(n, val, ctxt);
1102 Buf_AddByte(v->val, (Byte)' ');
1103 Buf_Append(v->val, val);
1104 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, Buf_Data(v->val)));
1110 * See if the given variable exists.
1113 * TRUE if it does, FALSE if it doesn't
1116 Var_Exists(const char *name, GNode *ctxt)
1121 n = VarPossiblyExpand(name, ctxt);
1122 v = VarFindAny(n, ctxt);
1133 * Return the value of the named variable in the given context
1136 * The value if the variable exists, NULL if it doesn't.
1139 Var_Value(const char name[], GNode *ctxt)
1144 n = VarPossiblyExpand(name, ctxt);
1145 v = VarFindAny(n, ctxt);
1150 return (Buf_Data(v->val));
1155 * Modify each of the words of the passed string using the given
1156 * function. Used to implement all modifiers.
1159 * A string of all the words modified appropriately.
1162 * Uses brk_string() so it invalidates any previous call to
1166 VarModify(const char *str, VarModifyProc *modProc, void *datum)
1169 Buffer *buf; /* Buffer for the new string */
1171 Boolean addSpace; /*
1172 * TRUE if need to add a space to
1173 * the buffer before adding the
1177 brk_string(&aa, str, FALSE);
1181 for (i = 1; i < aa.argc; i++)
1182 addSpace = (*modProc)(aa.argv[i], addSpace, buf, datum);
1185 return (Buf_Peel(buf));
1189 * Sort the words in the string.
1192 * str String whose words should be sorted
1193 * cmp A comparison function to control the ordering
1196 * A string containing the words sorted
1199 VarSortWords(const char *str, int (*cmp)(const void *, const void *))
1205 brk_string(&aa, str, FALSE);
1206 qsort(aa.argv + 1, aa.argc - 1, sizeof(char *), cmp);
1209 for (i = 1; i < aa.argc; i++) {
1210 Buf_Append(buf, aa.argv[i]);
1211 Buf_AddByte(buf, (Byte)((i < aa.argc - 1) ? ' ' : '\0'));
1215 return (Buf_Peel(buf));
1219 SortIncreasing(const void *l, const void *r)
1222 return (strcmp(*(const char* const*)l, *(const char* const*)r));
1226 * Remove adjacent duplicate words.
1229 * A string containing the resulting words.
1232 VarUniq(const char *str)
1235 Buffer *buf; /* Buffer for new string */
1239 brk_string(&aa, str, FALSE);
1242 for (j = 1, i = 2; i < aa.argc; i++) {
1243 if (strcmp(aa.argv[i], aa.argv[j]) != 0 && (++j != i))
1244 aa.argv[j] = aa.argv[i];
1249 for (i = 1; i < aa.argc; i++) {
1250 Buf_AddBytes(buf, strlen(aa.argv[i]), (Byte *)aa.argv[i]);
1251 if (i != aa.argc - 1)
1252 Buf_AddByte(buf, ' ');
1254 Buf_AddByte(buf, '\0');
1257 return (Buf_Peel(buf));
1261 * Pass through the tstr looking for 1) escaped delimiters,
1262 * '$'s and backslashes (place the escaped character in
1263 * uninterpreted) and 2) unescaped $'s that aren't before
1264 * the delimiter (expand the variable substitution).
1265 * Return the expanded string or NULL if the delimiter was missing
1266 * If pattern is specified, handle escaped ampersands, and replace
1267 * unescaped ampersands with the lhs of the pattern.
1270 * A string of all the words modified appropriately.
1271 * If length is specified, return the string length of the buffer
1272 * If flags is specified and the last character of the pattern is a
1273 * $ set the VAR_MATCH_END bit of flags.
1276 VarGetPattern(VarParser *vp, int delim, int *flags, VarPattern *patt)
1283 * Skim through until the matching delimiter is found; pick up
1284 * variable substitutions on the way. Also allow backslashes to quote
1285 * the delimiter, $, and \, but don't touch other backslashes.
1287 while (*vp->ptr != '\0') {
1288 if (*vp->ptr == delim) {
1291 } else if ((vp->ptr[0] == '\\') &&
1292 ((vp->ptr[1] == delim) ||
1293 (vp->ptr[1] == '\\') ||
1294 (vp->ptr[1] == '$') ||
1295 (vp->ptr[1] == '&' && patt != NULL))) {
1296 vp->ptr++; /* consume backslash */
1297 Buf_AddByte(buf, (Byte)vp->ptr[0]);
1300 } else if (vp->ptr[0] == '$') {
1301 if (vp->ptr[1] == delim) {
1302 if (flags == NULL) {
1303 Buf_AddByte(buf, (Byte)vp->ptr[0]);
1307 * Unescaped $ at end of patt =>
1308 * anchor patt at end.
1310 *flags |= VAR_MATCH_END;
1325 * If unescaped dollar sign not
1326 * before the delimiter, assume it's
1327 * a variable substitution and
1330 rval = VarParse(&subvp, &rfree);
1331 Buf_Append(buf, rval);
1334 vp->ptr = subvp.ptr;
1336 } else if (vp->ptr[0] == '&' && patt != NULL) {
1337 Buf_AppendBuf(buf, patt->lhs);
1340 Buf_AddByte(buf, (Byte)vp->ptr[0]);
1345 Buf_Destroy(buf, TRUE);
1350 * Make sure this variable is fully expanded.
1353 VarExpand(Var *v, VarParser *vp)
1358 if (v->flags & VAR_IN_USE) {
1359 Fatal("Variable %s is recursive.", v->name);
1363 v->flags |= VAR_IN_USE;
1366 * Before doing any modification, we have to make sure the
1367 * value has been fully expanded. If it looks like recursion
1368 * might be necessary (there's a dollar sign somewhere in the
1369 * variable's value) we just call Var_Subst to do any other
1370 * substitutions that are necessary. Note that the value
1371 * returned by Var_Subst will have been
1372 * dynamically-allocated, so it will need freeing when we
1375 value = Buf_Data(v->val);
1376 if (strchr(value, '$') == NULL) {
1377 result = strdup(value);
1381 buf = Var_Subst(value, vp->ctxt, vp->err);
1382 result = Buf_Peel(buf);
1385 v->flags &= ~VAR_IN_USE;
1391 * Select only those words in value that match the modifier.
1394 modifier_M(VarParser *vp, const char value[], char endc)
1401 modifier = vp->ptr[0];
1402 vp->ptr++; /* consume 'M' or 'N' */
1405 * Compress the \:'s out of the pattern, so allocate enough
1406 * room to hold the uncompressed pattern and compress the
1407 * pattern into that space.
1409 patt = estrdup(vp->ptr);
1411 while (vp->ptr[0] != '\0') {
1412 if (vp->ptr[0] == endc || vp->ptr[0] == ':') {
1415 if (vp->ptr[0] == '\\' &&
1416 (vp->ptr[1] == endc || vp->ptr[1] == ':')) {
1417 vp->ptr++; /* consume backslash */
1424 DEBUGF(VAR, ("Pattern :%s\n", patt));
1426 if (modifier == 'M') {
1427 newValue = VarModify(value, VarMatch, patt);
1429 newValue = VarModify(value, VarNoMatch, patt);
1437 * Substitute the replacement string for the pattern. The substitution
1438 * is applied to each word in value.
1441 modifier_S(VarParser *vp, const char value[], Var *v)
1449 vp->ptr++; /* consume 'S' */
1451 delim = *vp->ptr; /* used to find end of pattern */
1452 vp->ptr++; /* consume 1st delim */
1455 * If pattern begins with '^', it is anchored to the start of the
1456 * word -- skip over it and flag pattern.
1458 if (*vp->ptr == '^') {
1459 patt.flags |= VAR_MATCH_START;
1463 patt.lhs = VarGetPattern(vp, delim, &patt.flags, NULL);
1464 if (patt.lhs == NULL) {
1466 * LHS didn't end with the delim, complain and exit.
1468 Fatal("Unclosed substitution for %s (%c missing)",
1472 vp->ptr++; /* consume 2nd delim */
1474 patt.rhs = VarGetPattern(vp, delim, NULL, &patt);
1475 if (patt.rhs == NULL) {
1477 * RHS didn't end with the delim, complain and exit.
1479 Fatal("Unclosed substitution for %s (%c missing)",
1483 vp->ptr++; /* consume last delim */
1486 * Check for global substitution. If 'g' after the final delimiter,
1487 * substitution is global and is marked that way.
1489 if (vp->ptr[0] == 'g') {
1490 patt.flags |= VAR_SUB_GLOBAL;
1495 * Global substitution of the empty string causes an infinite number
1496 * of matches, unless anchored by '^' (start of string) or '$' (end
1497 * of string). Catch the infinite substitution here. Note that flags
1498 * can only contain the 3 bits we're interested in so we don't have
1499 * to mask unrelated bits. We can test for equality.
1501 if (Buf_Size(patt.lhs) == 0 && patt.flags == VAR_SUB_GLOBAL)
1502 Fatal("Global substitution of the empty string");
1504 newValue = VarModify(value, VarSubstitute, &patt);
1507 * Free the two strings.
1516 modifier_C(VarParser *vp, char value[], Var *v)
1525 vp->ptr++; /* consume 'C' */
1527 delim = *vp->ptr; /* delimiter between sections */
1529 vp->ptr++; /* consume 1st delim */
1531 patt.lhs = VarGetPattern(vp, delim, NULL, NULL);
1532 if (patt.lhs == NULL) {
1533 Fatal("Unclosed substitution for %s (%c missing)",
1537 vp->ptr++; /* consume 2st delim */
1539 patt.rhs = VarGetPattern(vp, delim, NULL, NULL);
1540 if (patt.rhs == NULL) {
1541 Fatal("Unclosed substitution for %s (%c missing)",
1545 vp->ptr++; /* consume last delim */
1549 patt.flags |= VAR_SUB_GLOBAL;
1550 vp->ptr++; /* consume 'g' */
1553 patt.flags |= VAR_SUB_ONE;
1554 vp->ptr++; /* consume '1' */
1560 error = regcomp(&patt.re, Buf_Data(patt.lhs), REG_EXTENDED);
1562 VarREError(error, &patt.re, "RE substitution error");
1568 patt.nsub = patt.re.re_nsub + 1;
1573 patt.matches = emalloc(patt.nsub * sizeof(regmatch_t));
1575 newValue = VarModify(value, VarRESubstitute, &patt);
1586 sysVvarsub(VarParser *vp, char startc, Var *v, const char value[])
1590 * This can either be a bogus modifier or a System-V substitution
1600 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1605 * First we make a pass through the string trying to verify it is a
1606 * SYSV-make-style translation: it must be: <string1>=<string2>)
1611 while (*cp != '\0' && cnt) {
1614 /* continue looking for endc */
1615 } else if (*cp == endc)
1617 else if (*cp == startc)
1623 if (*cp == endc && eqFound) {
1625 * Now we break this sucker into the lhs and rhs.
1627 patt.lhs = VarGetPattern(vp, '=', &patt.flags, NULL);
1628 if (patt.lhs == NULL) {
1629 Fatal("Unclosed substitution for %s (%c missing)",
1632 vp->ptr++; /* consume '=' */
1634 patt.rhs = VarGetPattern(vp, endc, NULL, &patt);
1635 if (patt.rhs == NULL) {
1636 Fatal("Unclosed substitution for %s (%c missing)",
1641 * SYSV modifications happen through the whole string. Note
1642 * the pattern is anchored at the end.
1644 newStr = VarModify(value, VarSYSVMatch, &patt);
1651 Error("Unknown modifier '%c'\n", *vp->ptr);
1653 while (*vp->ptr != '\0') {
1654 if (*vp->ptr == endc && *vp->ptr == ':') {
1666 * Quote shell meta-characters in the string
1672 Var_Quote(const char *str)
1675 /* This should cover most shells :-( */
1676 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
1678 buf = Buf_Init(MAKE_BSIZE);
1679 for (; *str; str++) {
1680 if (strchr(meta, *str) != NULL)
1681 Buf_AddByte(buf, (Byte)'\\');
1682 Buf_AddByte(buf, (Byte)*str);
1685 return (Buf_Peel(buf));
1690 * Now we need to apply any modifiers the user wants applied.
1693 * words which match the given <pattern>.
1694 * <pattern> is of the standard file
1697 * words which do not match the given <pattern>
1698 * <pattern> is of the standard file
1700 * :S<d><pat1><d><pat2><d>[g]
1701 * Substitute <pat2> for <pat1> in the value
1702 * :C<d><pat1><d><pat2><d>[g]
1703 * Substitute <pat2> for regex <pat1> in the value
1704 * :H Substitute the head of each word
1705 * :T Substitute the tail of each word
1706 * :E Substitute the extension (minus '.') of
1708 * :R Substitute the root of each word
1709 * (pathname minus the suffix).
1711 * Like :S, but the rhs goes to the end of
1713 * :U Converts variable to upper-case.
1714 * :L Converts variable to lower-case.
1715 * :O ("Order") Alphabeticaly sort words in variable.
1716 * :u ("uniq") Remove adjacent duplicate words.
1719 ParseModifier(VarParser *vp, char startc, Var *v, Boolean *freeResult)
1724 value = VarExpand(v, vp);
1727 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1729 vp->ptr++; /* consume first colon */
1731 while (*vp->ptr != '\0') {
1732 char *newStr; /* New value to return */
1734 if (*vp->ptr == endc) {
1738 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *vp->ptr, value));
1742 newStr = modifier_M(vp, value, endc);
1745 newStr = modifier_S(vp, value, v);
1748 newStr = modifier_C(vp, value, v);
1751 /* :tl :tu for OSF ODE & NetBSD make compatibility */
1752 switch (vp->ptr[1]) {
1764 if (vp->ptr[1] != endc && vp->ptr[1] != ':') {
1766 if ((vp->ptr[0] == 's') &&
1767 (vp->ptr[1] == 'h') &&
1768 (vp->ptr[2] == endc || vp->ptr[2] == ':')) {
1769 const char *error = NULL;
1773 Cmd_Exec(value, &error));
1775 newStr = estrdup("");
1779 Error(error, value);
1784 newStr = sysVvarsub(vp, startc, v, value);
1789 switch (vp->ptr[0]) {
1795 buf = Buf_Init(MAKE_BSIZE);
1796 for (cp = value; *cp; cp++)
1797 Buf_AddByte(buf, (Byte)tolower(*cp));
1799 newStr = Buf_Peel(buf);
1805 newStr = VarSortWords(value, SortIncreasing);
1809 newStr = Var_Quote(value);
1813 newStr = VarModify(value, VarTail, NULL);
1821 buf = Buf_Init(MAKE_BSIZE);
1822 for (cp = value; *cp; cp++)
1823 Buf_AddByte(buf, (Byte)toupper(*cp));
1825 newStr = Buf_Peel(buf);
1831 newStr = VarModify(value, VarHead, NULL);
1835 newStr = VarModify(value, VarSuffix, NULL);
1839 newStr = VarModify(value, VarRoot, NULL);
1843 newStr = VarUniq(value);
1847 newStr = sysVvarsub(vp, startc, v, value);
1853 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1859 *freeResult = (value == var_Error) ? FALSE : TRUE;
1861 if (vp->ptr[0] == ':') {
1862 vp->ptr++; /* consume colon */
1870 ParseRestModifier(VarParser *vp, char startc, Buffer *buf, Boolean *freeResult)
1877 vname = Buf_GetAll(buf, &vlen);
1879 v = VarFindAny(vname, vp->ctxt);
1881 value = ParseModifier(vp, startc, v, freeResult);
1885 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1888 * Still need to get to the end of the variable
1889 * specification, so kludge up a Var structure for the
1892 v = VarCreate(vname, NULL, VAR_JUNK);
1893 value = ParseModifier(vp, startc, v, freeResult);
1897 VarDestroy(v, TRUE);
1899 consumed = vp->ptr - vp->input + 1;
1901 * If substituting a local variable in a non-local context,
1902 * assume it's for dynamic source stuff. We have to handle
1903 * this specially and return the longhand for the variable
1904 * with the dollar sign escaped so it makes it back to the
1905 * caller. Only four of the local variables are treated
1906 * specially as they are the only four that will be set when
1907 * dynamic sources are expanded.
1910 (vlen == 2 && (vname[1] == 'F' || vname[1] == 'D'))) {
1911 if (strchr("!%*@", vname[0]) != NULL) {
1912 value = emalloc(consumed + 1);
1913 strncpy(value, vp->input, consumed);
1914 value[consumed] = '\0';
1922 isupper((unsigned char)vname[1])) {
1923 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1924 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1925 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1926 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1927 value = emalloc(consumed + 1);
1928 strncpy(value, vp->input, consumed);
1929 value[consumed] = '\0';
1936 *freeResult = FALSE;
1937 return (vp->err ? var_Error : varNoError);
1940 * Check for D and F forms of local variables since we're in
1941 * a local context and the name is the right length.
1944 (vname[1] == 'F' || vname[1] == 'D') &&
1945 (strchr("!%*<>@", vname[0]) != NULL)) {
1951 v = VarFindOnly(name, vp->ctxt);
1953 value = ParseModifier(vp, startc, v, freeResult);
1959 * Still need to get to the end of the variable
1960 * specification, so kludge up a Var structure for the
1963 v = VarCreate(vname, NULL, VAR_JUNK);
1964 value = ParseModifier(vp, startc, v, freeResult);
1968 VarDestroy(v, TRUE);
1970 *freeResult = FALSE;
1971 return (vp->err ? var_Error : varNoError);
1976 ParseRestEnd(VarParser *vp, Buffer *buf, Boolean *freeResult)
1983 vname = Buf_GetAll(buf, &vlen);
1985 v = VarFindAny(vname, vp->ctxt);
1987 value = VarExpand(v, vp);
1992 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1993 size_t consumed = vp->ptr - vp->input + 1;
1996 * If substituting a local variable in a non-local context,
1997 * assume it's for dynamic source stuff. We have to handle
1998 * this specially and return the longhand for the variable
1999 * with the dollar sign escaped so it makes it back to the
2000 * caller. Only four of the local variables are treated
2001 * specially as they are the only four that will be set when
2002 * dynamic sources are expanded.
2005 (vlen == 2 && (vname[1] == 'F' || vname[1] == 'D'))) {
2006 if (strchr("!%*@", vname[0]) != NULL) {
2007 value = emalloc(consumed + 1);
2008 strncpy(value, vp->input, consumed);
2009 value[consumed] = '\0';
2017 isupper((unsigned char)vname[1])) {
2018 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
2019 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
2020 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
2021 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
2022 value = emalloc(consumed + 1);
2023 strncpy(value, vp->input, consumed);
2024 value[consumed] = '\0';
2032 * Check for D and F forms of local variables since we're in
2033 * a local context and the name is the right length.
2036 (vname[1] == 'F' || vname[1] == 'D') &&
2037 (strchr("!%*<>@", vname[0]) != NULL)) {
2043 v = VarFindOnly(name, vp->ctxt);
2047 * No need for nested expansion or anything,
2048 * as we're the only one who sets these
2049 * things and we sure don't put nested
2050 * invocations in them...
2052 val = Buf_Data(v->val);
2054 if (vname[1] == 'D') {
2055 val = VarModify(val, VarHead, NULL);
2057 val = VarModify(val, VarTail, NULL);
2066 *freeResult = FALSE;
2067 return (vp->err ? var_Error : varNoError);
2071 * Parse a multi letter variable name, and return it's value.
2074 VarParseLong(VarParser *vp, Boolean *freeResult)
2081 buf = Buf_Init(MAKE_BSIZE);
2083 startc = vp->ptr[0];
2084 vp->ptr++; /* consume opening paren or brace */
2086 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
2089 * Process characters until we reach an end character or a colon,
2090 * replacing embedded variables as we go.
2092 while (*vp->ptr != '\0') {
2093 if (*vp->ptr == endc) {
2094 value = ParseRestEnd(vp, buf, freeResult);
2095 vp->ptr++; /* consume closing paren or brace */
2096 Buf_Destroy(buf, TRUE);
2099 } else if (*vp->ptr == ':') {
2100 value = ParseRestModifier(vp, startc, buf, freeResult);
2101 vp->ptr++; /* consume closing paren or brace */
2102 Buf_Destroy(buf, TRUE);
2105 } else if (*vp->ptr == '$') {
2116 rval = VarParse(&subvp, &rfree);
2117 if (rval == var_Error) {
2118 Fatal("Error expanding embedded variable.");
2120 Buf_Append(buf, rval);
2123 vp->ptr = subvp.ptr;
2125 Buf_AddByte(buf, (Byte)*vp->ptr);
2130 /* If we did not find the end character, return var_Error */
2131 Buf_Destroy(buf, TRUE);
2132 *freeResult = FALSE;
2137 * Parse a single letter variable name, and return it's value.
2140 VarParseShort(VarParser *vp, Boolean *freeResult)
2146 vname[0] = vp->ptr[0];
2149 vp->ptr++; /* consume single letter */
2151 v = VarFindAny(vname, vp->ctxt);
2153 value = VarExpand(v, vp);
2159 * If substituting a local variable in a non-local context, assume
2160 * it's for dynamic source stuff. We have to handle this specially
2161 * and return the longhand for the variable with the dollar sign
2162 * escaped so it makes it back to the caller. Only four of the local
2163 * variables are treated specially as they are the only four that
2164 * will be set when dynamic sources are expanded.
2166 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
2168 /* XXX: It looks like $% and $! are reversed here */
2172 return (estrdup("$(.TARGET)"));
2175 return (estrdup("$(.ARCHIVE)"));
2178 return (estrdup("$(.PREFIX)"));
2181 return (estrdup("$(.MEMBER)"));
2183 *freeResult = FALSE;
2184 return (vp->err ? var_Error : varNoError);
2188 /* Variable name was not found. */
2189 *freeResult = FALSE;
2190 return (vp->err ? var_Error : varNoError);
2194 VarParse(VarParser *vp, Boolean *freeResult)
2197 vp->ptr++; /* consume '$' or last letter of conditional */
2199 if (vp->ptr[0] == '\0') {
2200 /* Error, there is only a dollar sign in the input string. */
2201 *freeResult = FALSE;
2202 return (vp->err ? var_Error : varNoError);
2204 } else if (vp->ptr[0] == OPEN_PAREN || vp->ptr[0] == OPEN_BRACE) {
2205 /* multi letter variable name */
2206 return (VarParseLong(vp, freeResult));
2209 /* single letter variable name */
2210 return (VarParseShort(vp, freeResult));
2215 * Given the start of a variable invocation, extract the variable
2216 * name and find its value, then modify it according to the
2220 * The value of the variable or var_Error if the specification
2221 * is invalid. The number of characters in the specification
2222 * is placed in the variable pointed to by consumed. (for
2223 * invalid specifications, this is just 2 to skip the '$' and
2224 * the following letter, or 1 if '$' was the last character
2225 * in the string). A Boolean in *freeResult telling whether the
2226 * returned string should be freed by the caller.
2229 Var_Parse(const char input[], GNode *ctxt, Boolean err,
2230 size_t *consumed, Boolean *freeResult)
2241 value = VarParse(&vp, freeResult);
2242 *consumed += vp.ptr - vp.input;
2247 * Given the start of a variable invocation, determine the length
2248 * of the specification.
2251 * The number of characters in the specification. For invalid
2252 * specifications, this is just 2 to skip the '$' and the
2253 * following letter, or 1 if '$' was the last character in the
2257 Var_Match(const char input[], GNode *ctxt)
2269 value = VarParse(&vp, &freeResult);
2273 return (vp.ptr - vp.input);
2277 match_var(const char str[], const char var[])
2279 const char *start = str;
2282 str++; /* consume '$' */
2284 if (str[0] == OPEN_PAREN || str[0] == OPEN_BRACE) {
2285 str++; /* consume opening paren or brace */
2287 while (str[0] != '\0') {
2288 if (str[0] == '$') {
2290 * A variable inside the variable. We cannot
2291 * expand the external variable yet.
2293 return (str - start);
2294 } else if (str[0] == ':' ||
2295 str[0] == CLOSE_PAREN ||
2296 str[0] == CLOSE_BRACE) {
2297 len = str - (start + 2);
2299 if (strncmp(var, start + 2, len) == 0 && var[len] == '\0') {
2300 return (0); /* match */
2303 * Not the variable we want to
2306 return (str - start);
2312 return (str - start);
2314 /* Single letter variable name */
2315 if (var[1] == '\0' && var[0] == str[0]) {
2316 return (0); /* match */
2318 str++; /* consume variable name */
2319 return (str - start);
2325 * Substitute for all variables in the given string in the given
2326 * context If err is TRUE, Parse_Error will be called when an
2327 * undefined variable is encountered.
2330 * The resulting string.
2333 * None. The old string must be freed by the caller
2336 Var_Subst(const char *str, GNode *ctxt, Boolean err)
2338 Boolean errorReported;
2339 Buffer *buf; /* Buffer for forming things */
2342 * Set TRUE if an error has already been reported to prevent a
2343 * plethora of messages when recursing. XXXHB this comment sounds
2346 errorReported = FALSE;
2349 while (str[0] != '\0') {
2350 if ((str[0] == '$') && (str[1] == '$')) {
2352 * A dollar sign may be escaped with another dollar
2353 * sign. In such a case, we skip over the escape
2354 * character and store the dollar sign into the
2358 Buf_AddByte(buf, (Byte)str[0]);
2361 } else if (str[0] == '$') {
2362 /* Variable invocation. */
2373 rval = VarParse(&subvp, &rfree);
2376 * When we come down here, val should either point to
2377 * the value of this variable, suitably modified, or
2378 * be NULL. Length should be the total length of the
2379 * potential variable invocation (from $ to end
2382 if (rval == var_Error || rval == varNoError) {
2384 * If performing old-time variable
2385 * substitution, skip over the variable and
2386 * continue with the substitution. Otherwise,
2387 * store the dollar sign and advance str so
2388 * we continue with the string...
2394 * If variable is undefined, complain
2395 * and skip the variable. The
2396 * complaint will stop us from doing
2397 * anything when the file is parsed.
2399 if (!errorReported) {
2400 Parse_Error(PARSE_FATAL,
2401 "Undefined variable \"%.*s\"", subvp.ptr - subvp.input, str);
2403 errorReported = TRUE;
2406 Buf_AddByte(buf, (Byte)str[0]);
2411 * Copy all the characters from the variable
2412 * value straight into the new string.
2414 Buf_Append(buf, rval);
2421 Buf_AddByte(buf, (Byte)str[0]);
2430 * Substitute for all variables except if it is the same as 'var',
2431 * in the given string in the given context. If err is TRUE,
2432 * Parse_Error will be called when an undefined variable is
2436 * The resulting string.
2439 * None. The old string must be freed by the caller
2442 Var_SubstOnly(const char *var, const char *str, Boolean err)
2444 GNode *ctxt = VAR_GLOBAL;
2445 Boolean errorReported;
2446 Buffer *buf; /* Buffer for forming things */
2449 * Set TRUE if an error has already been reported to prevent a
2450 * plethora of messages when recursing. XXXHB this comment sounds
2453 errorReported = FALSE;
2456 while (str[0] != '\0') {
2457 if (str[0] == '$') {
2460 skip = match_var(str, var);
2462 Buf_AddBytes(buf, skip, str);
2465 /* Variable invocation. */
2476 rval = VarParse(&subvp, &rfree);
2479 * When we get down here, rval should either
2480 * point to the value of this variable, or be
2483 if (rval == var_Error || rval == varNoError) {
2485 * If performing old-time variable
2486 * substitution, skip over the
2487 * variable and continue with the
2488 * substitution. Otherwise, store the
2489 * dollar sign and advance str so we
2490 * continue with the string...
2496 * If variable is undefined,
2497 * complain and skip the
2498 * variable. The complaint
2499 * will stop us from doing
2500 * anything when the file is
2503 if (!errorReported) {
2504 Parse_Error(PARSE_FATAL,
2505 "Undefined variable \"%.*s\"", subvp.ptr - subvp.input, str);
2507 errorReported = TRUE;
2510 Buf_AddByte(buf, (Byte)str[0]);
2515 * Copy all the characters from the
2516 * variable value straight into the
2519 Buf_Append(buf, rval);
2527 Buf_AddByte(buf, (Byte)str[0]);
2536 * Initialize the module
2539 * The VAR_CMD and VAR_GLOBAL contexts are created
2542 Var_Init(char **env)
2546 VAR_CMD = Targ_NewGN("Command");
2547 VAR_ENV = Targ_NewGN("Environment");
2548 VAR_GLOBAL = Targ_NewGN("Global");
2551 * Copy user environment variables into ENV context.
2553 for (ptr = env; *ptr != NULL; ++ptr) {
2554 char *tmp = estrdup(*ptr);
2555 const char *name = tmp;
2556 char *sep = strchr(name, '=');
2557 const char *value = sep + 1;
2561 VarAdd(name, value, VAR_ENV);
2568 * Print all variables in global and command line contexts.
2576 printf("#*** Global Variables:\n");
2577 LST_FOREACH(ln, &VAR_GLOBAL->context) {
2579 printf("%-16s = %s\n", v->name, Buf_Data(v->val));
2582 printf("#*** Command-line Variables:\n");
2583 LST_FOREACH(ln, &VAR_CMD->context) {
2585 printf("%-16s = %s\n", v->name, Buf_Data(v->val));
2590 * Print the values of any variables requested by
2594 Var_Print(Lst *vlist, Boolean expandVars)
2599 LST_FOREACH(n, vlist) {
2600 name = Lst_Datum(n);
2608 v = emalloc(strlen(name) + 1 + 3);
2609 sprintf(v, "${%s}", name);
2611 value = Buf_Peel(Var_Subst(v, VAR_GLOBAL, FALSE));
2612 printf("%s\n", value);
2618 const char *value = Var_Value(name, VAR_GLOBAL);
2619 printf("%s\n", value != NULL ? value : "");