2 * Copyright (c) 1988, 1989, 1990, 1993
3 * The Regents of the University of California. All rights reserved.
4 * Copyright (c) 1989 by Berkeley Softworks
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the University of
21 * California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * @(#)var.c 8.3 (Berkeley) 3/19/94
39 * $FreeBSD: src/usr.bin/make/var.c,v 1.83 2005/02/11 10:49:01 harti Exp $
40 * $DragonFly: src/usr.bin/make/var.c,v 1.194 2005/04/21 23:03:13 okumoto Exp $
45 * Variable-handling functions
48 * Var_Set Set the value of a variable in the given
49 * context. The variable is created if it doesn't
50 * yet exist. The value and variable name need not
53 * Var_Append Append more characters to an existing variable
54 * in the given context. The variable needn't
55 * exist already -- it will be created if it doesn't.
56 * A space is placed between the old value and the
59 * Var_Exists See if a variable exists.
61 * Var_Value Return the value of a variable in a context or
62 * NULL if the variable is undefined.
64 * Var_Subst Substitute named variable, or all variables if
65 * NULL in a string using
66 * the given context as the top-most one. If the
67 * third argument is non-zero, Parse_Error is
68 * called if any variables are undefined.
70 * Var_Parse Parse a variable expansion from a string and
71 * return the result and the number of characters
74 * Var_Delete Delete a variable in a context.
76 * Var_Init Initialize this module.
79 * Var_Dump Print out all variables defined in the given
82 * XXX: There's a lot of duplication in these functions.
105 typedef struct VarParser {
106 const char *const input; /* pointer to input string */
107 const char *ptr; /* current parser pos in input str */
112 static char *VarParse(VarParser *, Boolean *);
115 * This is a harmless return value for Var_Parse that can be used by Var_Subst
116 * to determine if there was an error in parsing -- easier than returning
117 * a flag, as things outside this module don't give a hoot.
119 char var_Error[] = "";
122 * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
123 * set false. Why not just use a constant? Well, gcc likes to condense
124 * identical string instances...
126 static char varNoError[] = "";
129 * Internally, variables are contained in four different contexts.
130 * 1) the environment. They may not be changed. If an environment
131 * variable is appended-to, the result is placed in the global
133 * 2) the global context. Variables set in the Makefile are located in
134 * the global context. It is the penultimate context searched when
136 * 3) the command-line context. All variables set on the command line
137 * are placed in this context. They are UNALTERABLE once placed here.
138 * 4) the local context. Each target has associated with it a context
139 * list. On this list are located the structures describing such
140 * local variables as $(@) and $(*)
141 * The four contexts are searched in the reverse order from which they are
144 GNode *VAR_ENV; /* variables from the environment */
145 GNode *VAR_GLOBAL; /* variables from the makefile */
146 GNode *VAR_CMD; /* variables defined on the command-line */
148 #define OPEN_PAREN '('
149 #define CLOSE_PAREN ')'
150 #define OPEN_BRACE '{'
151 #define CLOSE_BRACE '}'
154 * Create a Var object.
156 * @param name Name of variable.
157 * @param value Value of variable.
158 * @param flags Flags set on variable.
161 VarCreate(const char name[], const char value[], int flags)
165 v = emalloc(sizeof(Var));
166 v->name = estrdup(name);
167 v->val = Buf_Init(0);
171 Buf_Append(v->val, value);
177 * Destroy a Var object.
179 * @param v Object to destroy.
180 * @param f true if internal buffer in Buffer object is to be
184 VarDestroy(Var *v, Boolean f)
187 Buf_Destroy(v->val, f);
194 * Remove the tail of the given word and place the result in the given
198 * TRUE if characters were added to the buffer (a space needs to be
199 * added to the buffer before the next word).
202 * The trimmed word is added to the buffer.
205 VarHead(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
209 slash = strrchr(word, '/');
212 Buf_AddByte(buf, (Byte)' ');
214 Buf_AppendRange(buf, word, slash);
217 * If no directory part, give . (q.v. the POSIX standard)
220 Buf_Append(buf, " .");
222 Buf_AddByte(buf, (Byte)'.');
230 * Remove the head of the given word and place the result in the given
234 * TRUE if characters were added to the buffer (a space needs to be
235 * added to the buffer before the next word).
238 * The trimmed word is added to the buffer.
241 VarTail(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
246 Buf_AddByte (buf, (Byte)' ');
249 slash = strrchr(word, '/');
252 Buf_Append(buf, slash);
254 Buf_Append(buf, word);
261 * Place the suffix of the given word in the given buffer.
264 * TRUE if characters were added to the buffer (a space needs to be
265 * added to the buffer before the next word).
268 * The suffix from the word is placed in the buffer.
271 VarSuffix(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
275 dot = strrchr(word, '.');
278 Buf_AddByte(buf, (Byte)' ');
281 Buf_Append(buf, dot);
289 * Remove the suffix of the given word and place the result in the
293 * TRUE if characters were added to the buffer (a space needs to be
294 * added to the buffer before the next word).
297 * The trimmed word is added to the buffer.
300 VarRoot(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
305 Buf_AddByte(buf, (Byte)' ');
308 dot = strrchr(word, '.');
310 Buf_AppendRange(buf, word, dot);
312 Buf_Append(buf, word);
319 * Place the word in the buffer if it matches the given pattern.
320 * Callback function for VarModify to implement the :M modifier.
321 * A space will be added if requested. A pattern is supplied
322 * which the word must match.
325 * TRUE if a space should be placed in the buffer before the next
329 * The word may be copied to the buffer.
332 VarMatch(const char *word, Boolean addSpace, Buffer *buf, void *pattern)
335 if (Str_Match(word, pattern)) {
337 Buf_AddByte(buf, (Byte)' ');
340 Buf_Append(buf, word);
348 * Place the word in the buffer if it matches the given pattern.
349 * Callback function for VarModify to implement the System V %
350 * modifiers. A space is added if requested.
353 * TRUE if a space should be placed in the buffer before the next
357 * The word may be copied to the buffer.
360 VarSYSVMatch(const char *word, Boolean addSpace, Buffer *buf, void *patp)
364 VarPattern *pat = (VarPattern *)patp;
367 Buf_AddByte(buf, (Byte)' ');
371 if ((ptr = Str_SYSVMatch(word, Buf_Data(pat->lhs), &len)) != NULL)
372 Str_SYSVSubst(buf, Buf_Data(pat->rhs), ptr, len);
374 Buf_Append(buf, word);
382 * Place the word in the buffer if it doesn't match the given pattern.
383 * Callback function for VarModify to implement the :N modifier. A
384 * space is added if requested.
387 * TRUE if a space should be placed in the buffer before the next
391 * The word may be copied to the buffer.
394 VarNoMatch(const char *word, Boolean addSpace, Buffer *buf, void *pattern)
397 if (!Str_Match(word, pattern)) {
399 Buf_AddByte(buf, (Byte)' ');
402 Buf_Append(buf, word);
409 * Perform a string-substitution on the given word, placing the
410 * result in the passed buffer. A space is added if requested.
413 * TRUE if a space is needed before more characters are added.
416 VarSubstitute(const char *word, Boolean addSpace, Buffer *buf, void *patternp)
418 size_t wordLen; /* Length of word */
419 const char *cp; /* General pointer */
420 VarPattern *pattern = patternp;
422 wordLen = strlen(word);
423 if (1) { /* substitute in each word of the variable */
425 * Break substitution down into simple anchored cases
426 * and if none of them fits, perform the general substitution
429 if ((pattern->flags & VAR_MATCH_START) &&
430 (strncmp(word, Buf_Data(pattern->lhs),
431 Buf_Size(pattern->lhs)) == 0)) {
433 * Anchored at start and beginning of word matches
436 if ((pattern->flags & VAR_MATCH_END) &&
437 (wordLen == Buf_Size(pattern->lhs))) {
439 * Also anchored at end and matches to the end
440 * (word is same length as pattern) add space
441 * and rhs only if rhs is non-null.
443 if (Buf_Size(pattern->rhs) != 0) {
445 Buf_AddByte(buf, (Byte)' ');
448 Buf_AppendBuf(buf, pattern->rhs);
451 } else if (pattern->flags & VAR_MATCH_END) {
453 * Doesn't match to end -- copy word wholesale
459 * Matches at start but need to copy in
460 * trailing characters.
462 if ((Buf_Size(pattern->rhs) + wordLen -
463 Buf_Size(pattern->lhs)) != 0) {
465 Buf_AddByte(buf, (Byte)' ');
469 Buf_AppendBuf(buf, pattern->rhs);
470 Buf_AddBytes(buf, wordLen -
471 Buf_Size(pattern->lhs),
472 (word + Buf_Size(pattern->lhs)));
475 } else if (pattern->flags & VAR_MATCH_START) {
477 * Had to match at start of word and didn't -- copy
482 } else if (pattern->flags & VAR_MATCH_END) {
484 * Anchored at end, Find only place match could occur
485 * (leftLen characters from the end of the word) and
486 * see if it does. Note that because the $ will be
487 * left at the end of the lhs, we have to use strncmp.
489 cp = word + (wordLen - Buf_Size(pattern->lhs));
490 if ((cp >= word) && (strncmp(cp, Buf_Data(pattern->lhs),
491 Buf_Size(pattern->lhs)) == 0)) {
493 * Match found. If we will place characters in
494 * the buffer, add a space before hand as
495 * indicated by addSpace, then stuff in the
496 * initial, unmatched part of the word followed
497 * by the right-hand-side.
499 if ((cp - word) + Buf_Size(pattern->rhs) != 0) {
501 Buf_AddByte(buf, (Byte)' ');
505 Buf_AppendRange(buf, word, cp);
506 Buf_AppendBuf(buf, pattern->rhs);
510 * Had to match at end and didn't. Copy entire
517 * Pattern is unanchored: search for the pattern in the
518 * word using strstr(3), copying unmatched portions and
519 * the right-hand-side for each match found, handling
520 * non-global substitutions correctly, etc. When the
521 * loop is done, any remaining part of the word (word
522 * and wordLen are adjusted accordingly through the
523 * loop) is copied straight into the buffer.
524 * addSpace is set FALSE as soon as a space is added
531 origSize = Buf_Size(buf);
533 cp = strstr(word, Buf_Data(pattern->lhs));
535 if (addSpace && (((cp - word) +
536 Buf_Size(pattern->rhs)) != 0)) {
537 Buf_AddByte(buf, (Byte)' ');
540 Buf_AppendRange(buf, word, cp);
541 Buf_AppendBuf(buf, pattern->rhs);
542 wordLen -= (cp - word) +
543 Buf_Size(pattern->lhs);
544 word = cp + Buf_Size(pattern->lhs);
545 if (wordLen == 0 || (pattern->flags &
546 VAR_SUB_GLOBAL) == 0) {
555 Buf_AddByte(buf, (Byte)' ');
557 Buf_AddBytes(buf, wordLen, (const Byte *)word);
561 * If added characters to the buffer, need to add a
562 * space before we add any more. If we didn't add any,
563 * just return the previous value of addSpace.
565 return ((Buf_Size(buf) != origSize) || addSpace);
568 * Common code for anchored substitutions:
569 * addSpace was set TRUE if characters were added to the buffer.
575 Buf_AddByte(buf, (Byte)' ');
577 Buf_AddBytes(buf, wordLen, (const Byte *)word);
583 * Perform a regex substitution on the given word, placing the
584 * result in the passed buffer. A space is added if requested.
587 * TRUE if a space is needed before more characters are added.
590 VarRESubstitute(const char *word, Boolean addSpace, Buffer *buf, void *patternp)
599 #define MAYBE_ADD_SPACE() \
600 if (addSpace && !added) \
601 Buf_AddByte(buf, (Byte)' '); \
608 if ((pat->flags & (VAR_SUB_ONE | VAR_SUB_MATCHED)) ==
609 (VAR_SUB_ONE | VAR_SUB_MATCHED)) {
613 xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
618 pat->flags |= VAR_SUB_MATCHED;
619 if (pat->matches[0].rm_so > 0) {
621 Buf_AddBytes(buf, pat->matches[0].rm_so,
625 for (rp = Buf_Data(pat->rhs); *rp; rp++) {
626 if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
628 Buf_AddByte(buf, (Byte)rp[1]);
631 } else if ((*rp == '&') ||
632 ((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
651 Error("No subexpression %s",
656 } else if ((pat->matches[n].rm_so == -1) &&
657 (pat->matches[n].rm_eo == -1)) {
658 Error("No match for subexpression %s",
664 subbuf = wp + pat->matches[n].rm_so;
665 sublen = pat->matches[n].rm_eo -
666 pat->matches[n].rm_so;
671 Buf_AddBytes(buf, sublen,
672 (const Byte *)subbuf);
676 Buf_AddByte(buf, (Byte)*rp);
679 wp += pat->matches[0].rm_eo;
680 if (pat->flags & VAR_SUB_GLOBAL) {
682 if (pat->matches[0].rm_so == 0 &&
683 pat->matches[0].rm_eo == 0) {
685 Buf_AddByte(buf, (Byte)*wp);
698 VarREError(xrv, &pat->re, "Unexpected regex error");
708 return (addSpace || added);
712 * Find a variable in a variable list.
715 VarLookup(Lst *vlist, const char *name)
719 LST_FOREACH(ln, vlist)
720 if (strcmp(((const Var *)Lst_Datum(ln))->name, name) == 0)
721 return (Lst_Datum(ln));
726 *-----------------------------------------------------------------------
727 * VarPossiblyExpand --
728 * Expand a variable name's embedded variables in the given context.
731 * The contents of name, possibly expanded.
732 *-----------------------------------------------------------------------
735 VarPossiblyExpand(const char *name, GNode *ctxt)
739 if (strchr(name, '$') != NULL) {
740 buf = Var_Subst(name, ctxt, 0);
741 return (Buf_Peel(buf));
743 return estrdup(name);
748 * If the variable name begins with a '.', it could very well be
749 * one of the local ones. We check the name against all the local
750 * variables and substitute the short version in for 'name' if it
751 * matches one of them.
754 VarLocal(const char name[])
756 if (name[0] == '.') {
759 if (!strcmp(name, ".ALLSRC"))
761 if (!strcmp(name, ".ARCHIVE"))
765 if (!strcmp(name, ".IMPSRC"))
769 if (!strcmp(name, ".MEMBER"))
773 if (!strcmp(name, ".OODATE"))
777 if (!strcmp(name, ".PREFIX"))
781 if (!strcmp(name, ".TARGET"))
792 * Find the given variable in the given context and the enviornment.
795 * A pointer to the structure describing the desired variable or
796 * NULL if the variable does not exist.
799 VarFindEnv(const char name[], GNode *ctxt)
803 name = VarLocal(name);
805 if ((var = VarLookup(&ctxt->context, name)) != NULL)
808 if ((var = VarLookup(&VAR_ENV->context, name)) != NULL)
815 * Look for the variable in the given context.
818 VarFindOnly(const char name[], GNode *ctxt)
821 return VarLookup(&ctxt->context, VarLocal(name));
825 * Look for the variable in all contexts.
828 VarFindAny(const char name[], GNode *ctxt)
830 Boolean localCheckEnvFirst;
834 name = VarLocal(name);
837 * Note whether this is one of the specific variables we were told
838 * through the -E flag to use environment-variable-override for.
840 localCheckEnvFirst = FALSE;
841 LST_FOREACH(ln, &envFirstVars) {
842 if (strcmp(Lst_Datum(ln), name) == 0) {
843 localCheckEnvFirst = TRUE;
849 * First look for the variable in the given context. If it's not there,
850 * look for it in VAR_CMD, VAR_GLOBAL and the environment,
851 * in that order, depending on the FIND_* flags in 'flags'
853 if ((var = VarLookup(&ctxt->context, name)) != NULL)
856 /* not there - try command line context */
857 if (ctxt != VAR_CMD) {
858 if ((var = VarLookup(&VAR_CMD->context, name)) != NULL)
862 /* not there - try global context, but only if not -e/-E */
863 if (ctxt != VAR_GLOBAL && (!checkEnvFirst && !localCheckEnvFirst)) {
864 if ((var = VarLookup(&VAR_GLOBAL->context, name)) != NULL)
868 if ((var = VarLookup(&VAR_ENV->context, name)) != NULL)
871 /* deferred check for the environment (in case of -e/-E) */
872 if ((ctxt != VAR_GLOBAL) && (checkEnvFirst || localCheckEnvFirst)) {
873 if ((var = VarLookup(&VAR_GLOBAL->context, name)) != NULL)
881 * Add a new variable of name name and value val to the given context.
887 * The new variable is placed at the front of the given context
888 * The name and val arguments are duplicated so they may
892 VarAdd(const char *name, const char *val, GNode *ctxt)
895 Lst_AtFront(&ctxt->context, VarCreate(name, val, 0));
896 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
900 *-----------------------------------------------------------------------
902 * Remove a variable from a context.
908 * The Var structure is removed and freed.
910 *-----------------------------------------------------------------------
913 Var_Delete(const char *name, GNode *ctxt)
917 DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
918 LST_FOREACH(ln, &ctxt->context) {
919 if (strcmp(((const Var *)Lst_Datum(ln))->name, name) == 0) {
920 VarDestroy(Lst_Datum(ln), TRUE);
921 Lst_Remove(&ctxt->context, ln);
928 *-----------------------------------------------------------------------
930 * Set the variable name to the value val in the given context.
936 * If the variable doesn't yet exist, a new record is created for it.
937 * Else the old value is freed and the new one stuck in its place
940 * The variable is searched for only in its context before being
941 * created in that context. I.e. if the context is VAR_GLOBAL,
942 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
943 * VAR_CMD->context is searched. This is done to avoid the literally
944 * thousands of unnecessary strcmp's that used to be done to
945 * set, say, $(@) or $(<).
946 *-----------------------------------------------------------------------
949 Var_Set(const char *name, const char *val, GNode *ctxt)
955 * We only look for a variable in the given context since anything
956 * set here will override anything in a lower context, so there's not
957 * much point in searching them all just to save a bit of memory...
959 n = VarPossiblyExpand(name, ctxt);
960 v = VarFindOnly(n, ctxt);
962 VarAdd(n, val, ctxt);
963 if (ctxt == VAR_CMD) {
965 * Any variables given on the command line
966 * are automatically exported to the
967 * environment (as per POSIX standard)
973 Buf_Append(v->val, val);
975 if (ctxt == VAR_CMD || (v->flags & VAR_TO_ENV)) {
977 * Any variables given on the command line
978 * are automatically exported to the
979 * environment (as per POSIX standard)
986 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, val));
992 * Set the VAR_TO_ENV flag on a variable
995 Var_SetEnv(const char *name, GNode *ctxt)
999 v = VarFindOnly(name, VAR_CMD);
1002 * Do not allow .EXPORT: to be set on variables
1003 * from the comand line or MAKEFLAGS.
1006 "Warning: Did not set .EXPORT: on %s because it "
1007 "is from the comand line or MAKEFLAGS", name);
1011 v = VarFindAny(name, ctxt);
1013 Lst_AtFront(&VAR_ENV->context,
1014 VarCreate(name, NULL, VAR_TO_ENV));
1015 setenv(name, "", 1);
1016 Error("Warning: .EXPORT: set on undefined variable %s", name);
1018 if ((v->flags & VAR_TO_ENV) == 0) {
1019 v->flags |= VAR_TO_ENV;
1020 setenv(v->name, Buf_Data(v->val), 1);
1026 *-----------------------------------------------------------------------
1028 * The variable of the given name has the given value appended to it in
1029 * the given context.
1035 * If the variable doesn't exist, it is created. Else the strings
1036 * are concatenated (with a space in between).
1039 * Only if the variable is being sought in the global context is the
1040 * environment searched.
1041 * XXX: Knows its calling circumstances in that if called with ctxt
1042 * an actual target, it will only search that context since only
1043 * a local variable could be being appended to. This is actually
1044 * a big win and must be tolerated.
1045 *-----------------------------------------------------------------------
1048 Var_Append(const char *name, const char *val, GNode *ctxt)
1053 n = VarPossiblyExpand(name, ctxt);
1054 if (ctxt == VAR_GLOBAL) {
1055 v = VarFindEnv(n, ctxt);
1057 v = VarFindOnly(n, ctxt);
1060 VarAdd(n, val, ctxt);
1062 Buf_AddByte(v->val, (Byte)' ');
1063 Buf_Append(v->val, val);
1064 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, Buf_Data(v->val)));
1070 *-----------------------------------------------------------------------
1072 * See if the given variable exists.
1075 * TRUE if it does, FALSE if it doesn't
1080 *-----------------------------------------------------------------------
1083 Var_Exists(const char *name, GNode *ctxt)
1088 n = VarPossiblyExpand(name, ctxt);
1089 v = VarFindAny(n, ctxt);
1100 *-----------------------------------------------------------------------
1102 * Return the value of the named variable in the given context
1105 * The value if the variable exists, NULL if it doesn't
1109 *-----------------------------------------------------------------------
1112 Var_Value(const char *name, GNode *ctxt, char **frp)
1118 n = VarPossiblyExpand(name, ctxt);
1119 v = VarFindAny(n, ctxt);
1124 p = Buf_Data(v->val);
1132 *-----------------------------------------------------------------------
1134 * Modify each of the words of the passed string using the given
1135 * function. Used to implement all modifiers.
1138 * A string of all the words modified appropriately.
1141 * Uses brk_string() so it invalidates any previous call to
1144 *-----------------------------------------------------------------------
1147 VarModify(const char *str, VarModifyProc *modProc, void *datum)
1149 char **av; /* word list [first word does not count] */
1151 Buffer *buf; /* Buffer for the new string */
1152 Boolean addSpace; /* TRUE if need to add a space to the buffer
1153 * before adding the trimmed word */
1156 av = brk_string(str, &ac, FALSE);
1161 for (i = 1; i < ac; i++)
1162 addSpace = (*modProc)(av[i], addSpace, buf, datum);
1164 return (Buf_Peel(buf));
1168 *-----------------------------------------------------------------------
1170 * Sort the words in the string.
1173 * str String whose words should be sorted
1174 * cmp A comparison function to control the ordering
1177 * A string containing the words sorted
1180 * Uses brk_string() so it invalidates any previous call to
1183 *-----------------------------------------------------------------------
1186 VarSortWords(const char *str, int (*cmp)(const void *, const void *))
1193 av = brk_string(str, &ac, FALSE);
1194 qsort(av + 1, ac - 1, sizeof(char *), cmp);
1197 for (i = 1; i < ac; i++) {
1198 Buf_Append(buf, av[i]);
1199 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
1202 return (Buf_Peel(buf));
1206 SortIncreasing(const void *l, const void *r)
1209 return (strcmp(*(const char* const*)l, *(const char* const*)r));
1213 *-----------------------------------------------------------------------
1215 * Pass through the tstr looking for 1) escaped delimiters,
1216 * '$'s and backslashes (place the escaped character in
1217 * uninterpreted) and 2) unescaped $'s that aren't before
1218 * the delimiter (expand the variable substitution).
1219 * Return the expanded string or NULL if the delimiter was missing
1220 * If pattern is specified, handle escaped ampersands, and replace
1221 * unescaped ampersands with the lhs of the pattern.
1224 * A string of all the words modified appropriately.
1225 * If length is specified, return the string length of the buffer
1226 * If flags is specified and the last character of the pattern is a
1227 * $ set the VAR_MATCH_END bit of flags.
1231 *-----------------------------------------------------------------------
1234 VarGetPattern(VarParser *vp, int delim, int *flags, VarPattern *patt)
1241 * Skim through until the matching delimiter is found; pick up
1242 * variable substitutions on the way. Also allow backslashes to quote
1243 * the delimiter, $, and \, but don't touch other backslashes.
1245 while (*vp->ptr != '\0') {
1246 if (*vp->ptr == delim) {
1249 } else if ((vp->ptr[0] == '\\') &&
1250 ((vp->ptr[1] == delim) ||
1251 (vp->ptr[1] == '\\') ||
1252 (vp->ptr[1] == '$') ||
1253 (vp->ptr[1] == '&' && patt != NULL))) {
1254 vp->ptr++; /* consume backslash */
1255 Buf_AddByte(buf, (Byte)vp->ptr[0]);
1258 } else if (vp->ptr[0] == '$') {
1259 if (vp->ptr[1] == delim) {
1260 if (flags == NULL) {
1261 Buf_AddByte(buf, (Byte)vp->ptr[0]);
1265 * Unescaped $ at end of patt =>
1266 * anchor patt at end.
1268 *flags |= VAR_MATCH_END;
1283 * If unescaped dollar sign not
1284 * before the delimiter, assume it's
1285 * a variable substitution and
1288 rval = VarParse(&subvp, &rfree);
1289 Buf_Append(buf, rval);
1292 vp->ptr = subvp.ptr;
1294 } else if (vp->ptr[0] == '&' && patt != NULL) {
1295 Buf_AppendBuf(buf, patt->lhs);
1298 Buf_AddByte(buf, (Byte)vp->ptr[0]);
1303 Buf_Destroy(buf, TRUE);
1308 *-----------------------------------------------------------------------
1310 * Quote shell meta-characters in the string
1318 *-----------------------------------------------------------------------
1321 Var_Quote(const char *str)
1324 /* This should cover most shells :-( */
1325 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
1327 buf = Buf_Init(MAKE_BSIZE);
1328 for (; *str; str++) {
1329 if (strchr(meta, *str) != NULL)
1330 Buf_AddByte(buf, (Byte)'\\');
1331 Buf_AddByte(buf, (Byte)*str);
1334 return (Buf_Peel(buf));
1338 *-----------------------------------------------------------------------
1340 * Print the error caused by a regcomp or regexec call.
1346 * An error gets printed.
1348 *-----------------------------------------------------------------------
1351 VarREError(int err, regex_t *pat, const char *str)
1356 errlen = regerror(err, pat, 0, 0);
1357 errbuf = emalloc(errlen);
1358 regerror(err, pat, errbuf, errlen);
1359 Error("%s: %s", str, errbuf);
1364 * Make sure this variable is fully expanded.
1367 VarExpand(Var *v, VarParser *vp)
1372 if (v->flags & VAR_IN_USE) {
1373 Fatal("Variable %s is recursive.", v->name);
1377 v->flags |= VAR_IN_USE;
1380 * Before doing any modification, we have to make sure the
1381 * value has been fully expanded. If it looks like recursion
1382 * might be necessary (there's a dollar sign somewhere in the
1383 * variable's value) we just call Var_Subst to do any other
1384 * substitutions that are necessary. Note that the value
1385 * returned by Var_Subst will have been
1386 * dynamically-allocated, so it will need freeing when we
1389 value = Buf_Data(v->val);
1390 if (strchr(value, '$') == NULL) {
1391 result = strdup(value);
1395 buf = Var_Subst(value, vp->ctxt, vp->err);
1396 result = Buf_Peel(buf);
1399 v->flags &= ~VAR_IN_USE;
1405 * Select only those words in value that match the modifier.
1408 modifier_M(VarParser *vp, const char value[], char endc)
1415 modifier = vp->ptr[0];
1416 vp->ptr++; /* consume 'M' or 'N' */
1419 * Compress the \:'s out of the pattern, so allocate enough
1420 * room to hold the uncompressed pattern and compress the
1421 * pattern into that space.
1423 patt = estrdup(vp->ptr);
1425 while (vp->ptr[0] != '\0') {
1426 if (vp->ptr[0] == endc || vp->ptr[0] == ':') {
1429 if (vp->ptr[0] == '\\' &&
1430 (vp->ptr[1] == endc || vp->ptr[1] == ':')) {
1431 vp->ptr++; /* consume backslash */
1439 if (modifier == 'M') {
1440 newValue = VarModify(value, VarMatch, patt);
1442 newValue = VarModify(value, VarNoMatch, patt);
1450 * Substitute the replacement string for the pattern. The substitution
1451 * is applied to each word in value.
1454 modifier_S(VarParser *vp, const char value[], Var *v)
1462 vp->ptr++; /* consume 'S' */
1464 delim = *vp->ptr; /* used to find end of pattern */
1465 vp->ptr++; /* consume 1st delim */
1468 * If pattern begins with '^', it is anchored to the start of the
1469 * word -- skip over it and flag pattern.
1471 if (*vp->ptr == '^') {
1472 patt.flags |= VAR_MATCH_START;
1476 patt.lhs = VarGetPattern(vp, delim, &patt.flags, NULL);
1477 if (patt.lhs == NULL) {
1479 * LHS didn't end with the delim, complain and exit.
1481 Fatal("Unclosed substitution for %s (%c missing)",
1485 vp->ptr++; /* consume 2nd delim */
1487 patt.rhs = VarGetPattern(vp, delim, NULL, &patt);
1488 if (patt.rhs == NULL) {
1490 * RHS didn't end with the delim, complain and exit.
1492 Fatal("Unclosed substitution for %s (%c missing)",
1496 vp->ptr++; /* consume last delim */
1499 * Check for global substitution. If 'g' after the final delimiter,
1500 * substitution is global and is marked that way.
1502 if (vp->ptr[0] == 'g') {
1503 patt.flags |= VAR_SUB_GLOBAL;
1508 * Global substitution of the empty string causes an infinite number
1509 * of matches, unless anchored by '^' (start of string) or '$' (end
1510 * of string). Catch the infinite substitution here. Note that flags
1511 * can only contain the 3 bits we're interested in so we don't have
1512 * to mask unrelated bits. We can test for equality.
1514 if (Buf_Size(patt.lhs) == 0 && patt.flags == VAR_SUB_GLOBAL)
1515 Fatal("Global substitution of the empty string");
1517 newValue = VarModify(value, VarSubstitute, &patt);
1520 * Free the two strings.
1529 modifier_C(VarParser *vp, char value[], Var *v)
1538 vp->ptr++; /* consume 'C' */
1540 delim = *vp->ptr; /* delimiter between sections */
1542 vp->ptr++; /* consume 1st delim */
1544 patt.lhs = VarGetPattern(vp, delim, NULL, NULL);
1545 if (patt.lhs == NULL) {
1546 Fatal("Unclosed substitution for %s (%c missing)",
1550 vp->ptr++; /* consume 2st delim */
1552 patt.rhs = VarGetPattern(vp, delim, NULL, NULL);
1553 if (patt.rhs == NULL) {
1554 Fatal("Unclosed substitution for %s (%c missing)",
1558 vp->ptr++; /* consume last delim */
1562 patt.flags |= VAR_SUB_GLOBAL;
1563 vp->ptr++; /* consume 'g' */
1566 patt.flags |= VAR_SUB_ONE;
1567 vp->ptr++; /* consume '1' */
1573 error = regcomp(&patt.re, Buf_Data(patt.lhs), REG_EXTENDED);
1575 VarREError(error, &patt.re, "RE substitution error");
1581 patt.nsub = patt.re.re_nsub + 1;
1586 patt.matches = emalloc(patt.nsub * sizeof(regmatch_t));
1588 newValue = VarModify(value, VarRESubstitute, &patt);
1599 sysVvarsub(VarParser *vp, char startc, Var *v, const char value[])
1603 * This can either be a bogus modifier or a System-V substitution
1613 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1618 * First we make a pass through the string trying to verify it is a
1619 * SYSV-make-style translation: it must be: <string1>=<string2>)
1624 while (*cp != '\0' && cnt) {
1627 /* continue looking for endc */
1628 } else if (*cp == endc)
1630 else if (*cp == startc)
1636 if (*cp == endc && eqFound) {
1638 * Now we break this sucker into the lhs and rhs.
1640 patt.lhs = VarGetPattern(vp, '=', &patt.flags, NULL);
1641 if (patt.lhs == NULL) {
1642 Fatal("Unclosed substitution for %s (%c missing)",
1645 vp->ptr++; /* consume '=' */
1647 patt.rhs = VarGetPattern(vp, endc, NULL, &patt);
1648 if (patt.rhs == NULL) {
1649 Fatal("Unclosed substitution for %s (%c missing)",
1654 * SYSV modifications happen through the whole string. Note
1655 * the pattern is anchored at the end.
1657 newStr = VarModify(value, VarSYSVMatch, &patt);
1664 Error("Unknown modifier '%c'\n", *vp->ptr);
1666 while (*vp->ptr != '\0') {
1667 if (*vp->ptr == endc && *vp->ptr == ':') {
1679 * Now we need to apply any modifiers the user wants applied.
1682 * words which match the given <pattern>.
1683 * <pattern> is of the standard file
1685 * :S<d><pat1><d><pat2><d>[g]
1686 * Substitute <pat2> for <pat1> in the value
1687 * :C<d><pat1><d><pat2><d>[g]
1688 * Substitute <pat2> for regex <pat1> in the value
1689 * :H Substitute the head of each word
1690 * :T Substitute the tail of each word
1691 * :E Substitute the extension (minus '.') of
1693 * :R Substitute the root of each word
1694 * (pathname minus the suffix).
1696 * Like :S, but the rhs goes to the end of
1698 * :U Converts variable to upper-case.
1699 * :L Converts variable to lower-case.
1701 * XXXHB update this comment or remove it and point to the man page.
1704 ParseModifier(VarParser *vp, char startc, Var *v, Boolean *freeResult)
1709 value = VarExpand(v, vp);
1712 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1714 vp->ptr++; /* consume first colon */
1716 while (*vp->ptr != '\0') {
1717 char *newStr; /* New value to return */
1719 if (*vp->ptr == endc) {
1723 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *vp->ptr, value));
1727 newStr = modifier_M(vp, value, endc);
1730 newStr = modifier_S(vp, value, v);
1733 newStr = modifier_C(vp, value, v);
1736 if (vp->ptr[1] != endc && vp->ptr[1] != ':') {
1738 if ((vp->ptr[0] == 's') &&
1739 (vp->ptr[1] == 'h') &&
1740 (vp->ptr[2] == endc || vp->ptr[2] == ':')) {
1745 Cmd_Exec(value, &error));
1747 newStr = estrdup("");
1751 Error(error, value);
1756 newStr = sysVvarsub(vp, startc, v, value);
1761 switch (vp->ptr[0]) {
1766 buf = Buf_Init(MAKE_BSIZE);
1767 for (cp = value; *cp; cp++)
1768 Buf_AddByte(buf, (Byte)tolower(*cp));
1770 newStr = Buf_Peel(buf);
1776 newStr = VarSortWords(value, SortIncreasing);
1780 newStr = Var_Quote(value);
1784 newStr = VarModify(value, VarTail, NULL);
1791 buf = Buf_Init(MAKE_BSIZE);
1792 for (cp = value; *cp; cp++)
1793 Buf_AddByte(buf, (Byte)toupper(*cp));
1795 newStr = Buf_Peel(buf);
1801 newStr = VarModify(value, VarHead, NULL);
1805 newStr = VarModify(value, VarSuffix, NULL);
1809 newStr = VarModify(value, VarRoot, NULL);
1813 newStr = sysVvarsub(vp, startc, v, value);
1819 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1825 *freeResult = (value == var_Error) ? FALSE : TRUE;
1827 if (vp->ptr[0] == ':') {
1828 vp->ptr++; /* consume colon */
1836 ParseRestModifier(VarParser *vp, char startc, Buffer *buf, Boolean *freeResult)
1843 vname = Buf_GetAll(buf, &vlen);
1845 v = VarFindAny(vname, vp->ctxt);
1847 value = ParseModifier(vp, startc, v, freeResult);
1851 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1854 * Still need to get to the end of the variable
1855 * specification, so kludge up a Var structure for the
1858 v = VarCreate(vname, NULL, VAR_JUNK);
1859 value = ParseModifier(vp, startc, v, freeResult);
1863 VarDestroy(v, TRUE);
1865 consumed = vp->ptr - vp->input + 1;
1867 * If substituting a local variable in a non-local context,
1868 * assume it's for dynamic source stuff. We have to handle
1869 * this specially and return the longhand for the variable
1870 * with the dollar sign escaped so it makes it back to the
1871 * caller. Only four of the local variables are treated
1872 * specially as they are the only four that will be set when
1873 * dynamic sources are expanded.
1876 (vlen == 2 && (vname[1] == 'F' || vname[1] == 'D'))) {
1877 if (strchr("!%*@", vname[0]) != NULL) {
1878 value = emalloc(consumed + 1);
1879 strncpy(value, vp->input, consumed);
1880 value[consumed] = '\0';
1888 isupper((unsigned char)vname[1])) {
1889 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1890 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1891 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1892 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1893 value = emalloc(consumed + 1);
1894 strncpy(value, vp->input, consumed);
1895 value[consumed] = '\0';
1902 *freeResult = FALSE;
1903 return (vp->err ? var_Error : varNoError);
1906 * Check for D and F forms of local variables since we're in
1907 * a local context and the name is the right length.
1910 (vname[1] == 'F' || vname[1] == 'D') &&
1911 (strchr("!%*<>@", vname[0]) != NULL)) {
1917 v = VarFindOnly(name, vp->ctxt);
1919 value = ParseModifier(vp, startc, v, freeResult);
1925 * Still need to get to the end of the variable
1926 * specification, so kludge up a Var structure for the
1929 v = VarCreate(vname, NULL, VAR_JUNK);
1930 value = ParseModifier(vp, startc, v, freeResult);
1934 VarDestroy(v, TRUE);
1936 *freeResult = FALSE;
1937 return (vp->err ? var_Error : varNoError);
1942 ParseRestEnd(VarParser *vp, Buffer *buf, Boolean *freeResult)
1949 vname = Buf_GetAll(buf, &vlen);
1951 v = VarFindAny(vname, vp->ctxt);
1953 value = VarExpand(v, vp);
1958 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1959 size_t consumed = vp->ptr - vp->input + 1;
1962 * If substituting a local variable in a non-local context,
1963 * assume it's for dynamic source stuff. We have to handle
1964 * this specially and return the longhand for the variable
1965 * with the dollar sign escaped so it makes it back to the
1966 * caller. Only four of the local variables are treated
1967 * specially as they are the only four that will be set when
1968 * dynamic sources are expanded.
1971 (vlen == 2 && (vname[1] == 'F' || vname[1] == 'D'))) {
1972 if (strchr("!%*@", vname[0]) != NULL) {
1973 value = emalloc(consumed + 1);
1974 strncpy(value, vp->input, consumed);
1975 value[consumed] = '\0';
1983 isupper((unsigned char)vname[1])) {
1984 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1985 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1986 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1987 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1988 value = emalloc(consumed + 1);
1989 strncpy(value, vp->input, consumed);
1990 value[consumed] = '\0';
1998 * Check for D and F forms of local variables since we're in
1999 * a local context and the name is the right length.
2002 (vname[1] == 'F' || vname[1] == 'D') &&
2003 (strchr("!%*<>@", vname[0]) != NULL)) {
2009 v = VarFindOnly(name, vp->ctxt);
2013 * No need for nested expansion or anything,
2014 * as we're the only one who sets these
2015 * things and we sure don't put nested
2016 * invocations in them...
2018 val = Buf_Data(v->val);
2020 if (vname[1] == 'D') {
2021 val = VarModify(val, VarHead, NULL);
2023 val = VarModify(val, VarTail, NULL);
2032 *freeResult = FALSE;
2033 return (vp->err ? var_Error : varNoError);
2037 * Parse a multi letter variable name, and return it's value.
2040 VarParseLong(VarParser *vp, Boolean *freeResult)
2047 buf = Buf_Init(MAKE_BSIZE);
2049 startc = vp->ptr[0];
2050 vp->ptr++; /* consume opening paren or brace */
2052 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
2055 * Process characters until we reach an end character or a colon,
2056 * replacing embedded variables as we go.
2058 while (*vp->ptr != '\0') {
2059 if (*vp->ptr == endc) {
2060 value = ParseRestEnd(vp, buf, freeResult);
2061 vp->ptr++; /* consume closing paren or brace */
2062 Buf_Destroy(buf, TRUE);
2065 } else if (*vp->ptr == ':') {
2066 value = ParseRestModifier(vp, startc, buf, freeResult);
2067 vp->ptr++; /* consume closing paren or brace */
2068 Buf_Destroy(buf, TRUE);
2071 } else if (*vp->ptr == '$') {
2082 rval = VarParse(&subvp, &rfree);
2083 if (rval == var_Error) {
2084 Fatal("Error expanding embedded variable.");
2086 Buf_Append(buf, rval);
2089 vp->ptr = subvp.ptr;
2091 Buf_AddByte(buf, (Byte)*vp->ptr);
2096 /* If we did not find the end character, return var_Error */
2097 Buf_Destroy(buf, TRUE);
2098 *freeResult = FALSE;
2103 * Parse a single letter variable name, and return it's value.
2106 VarParseShort(VarParser *vp, Boolean *freeResult)
2112 vname[0] = vp->ptr[0];
2115 vp->ptr++; /* consume single letter */
2117 v = VarFindAny(vname, vp->ctxt);
2119 value = VarExpand(v, vp);
2125 * If substituting a local variable in a non-local context, assume
2126 * it's for dynamic source stuff. We have to handle this specially
2127 * and return the longhand for the variable with the dollar sign
2128 * escaped so it makes it back to the caller. Only four of the local
2129 * variables are treated specially as they are the only four that
2130 * will be set when dynamic sources are expanded.
2132 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
2134 /* XXX: It looks like $% and $! are reversed here */
2138 return (estrdup("$(.TARGET)"));
2141 return (estrdup("$(.ARCHIVE)"));
2144 return (estrdup("$(.PREFIX)"));
2147 return (estrdup("$(.MEMBER)"));
2149 *freeResult = FALSE;
2150 return (vp->err ? var_Error : varNoError);
2154 /* Variable name was not found. */
2155 *freeResult = FALSE;
2156 return (vp->err ? var_Error : varNoError);
2160 VarParse(VarParser *vp, Boolean *freeResult)
2163 vp->ptr++; /* consume '$' or last letter of conditional */
2165 if (vp->ptr[0] == '\0') {
2166 /* Error, there is only a dollar sign in the input string. */
2167 *freeResult = FALSE;
2168 return (vp->err ? var_Error : varNoError);
2170 } else if (vp->ptr[0] == OPEN_PAREN || vp->ptr[0] == OPEN_BRACE) {
2171 /* multi letter variable name */
2172 return (VarParseLong(vp, freeResult));
2175 /* single letter variable name */
2176 return (VarParseShort(vp, freeResult));
2181 *-----------------------------------------------------------------------
2183 * Given the start of a variable invocation, extract the variable
2184 * name and find its value, then modify it according to the
2188 * The value of the variable or var_Error if the specification
2189 * is invalid. The number of characters in the specification
2190 * is placed in the variable pointed to by consumed. (for
2191 * invalid specifications, this is just 2 to skip the '$' and
2192 * the following letter, or 1 if '$' was the last character
2193 * in the string). A Boolean in *freeResult telling whether the
2194 * returned string should be freed by the caller.
2198 *-----------------------------------------------------------------------
2201 Var_Parse(const char input[], GNode *ctxt, Boolean err,
2202 size_t *consumed, Boolean *freeResult)
2213 value = VarParse(&vp, freeResult);
2214 *consumed += vp.ptr - vp.input;
2221 * The number of characters in the specification. For invalid
2222 * specifications, this is just 2 to skip the '$' and the
2223 * following letter, or 1 if '$' was the last character in the
2227 Var_Match(const char input[], GNode *ctxt)
2239 value = VarParse(&vp, &freeResult);
2243 return (vp.ptr - vp.input);
2247 *-----------------------------------------------------------------------
2249 * Substitute for all variables in the given string in the given context
2250 * If err is TRUE, Parse_Error will be called when an undefined
2251 * variable is encountered.
2254 * The resulting string.
2257 * None. The old string must be freed by the caller
2258 *-----------------------------------------------------------------------
2261 Var_Subst(const char *str, GNode *ctxt, Boolean err)
2263 Boolean errorReported;
2264 Buffer *buf; /* Buffer for forming things */
2267 * Set TRUE if an error has already been reported to prevent a
2268 * plethora of messages when recursing. XXXHB this comment sounds
2271 errorReported = FALSE;
2274 while (str[0] != '\0') {
2275 if ((str[0] == '$') && (str[1] == '$')) {
2277 * A dollar sign may be escaped with another dollar
2278 * sign. In such a case, we skip over the escape
2279 * character and store the dollar sign into the
2283 Buf_AddByte(buf, (Byte)str[0]);
2286 } else if (str[0] == '$') {
2287 /* Variable invocation. */
2298 rval = VarParse(&subvp, &rfree);
2301 * When we come down here, val should either point to
2302 * the value of this variable, suitably modified, or
2303 * be NULL. Length should be the total length of the
2304 * potential variable invocation (from $ to end
2307 if (rval == var_Error || rval == varNoError) {
2309 * If performing old-time variable
2310 * substitution, skip over the variable and
2311 * continue with the substitution. Otherwise,
2312 * store the dollar sign and advance str so
2313 * we continue with the string...
2319 * If variable is undefined, complain
2320 * and skip the variable. The
2321 * complaint will stop us from doing
2322 * anything when the file is parsed.
2324 if (!errorReported) {
2325 Parse_Error(PARSE_FATAL,
2326 "Undefined variable \"%.*s\"", subvp.ptr - subvp.input, str);
2328 errorReported = TRUE;
2331 Buf_AddByte(buf, (Byte)str[0]);
2336 * Copy all the characters from the variable
2337 * value straight into the new string.
2339 Buf_Append(buf, rval);
2346 Buf_AddByte(buf, (Byte)str[0]);
2355 match_var(const char str[], const char var[])
2357 const char *start = str;
2360 str++; /* consume '$' */
2362 if (str[0] == OPEN_PAREN || str[0] == OPEN_BRACE) {
2363 str++; /* consume opening paren or brace */
2365 while (str[0] != '\0') {
2366 if (str[0] == '$') {
2368 * A variable inside the variable. We cannot
2369 * expand the external variable yet.
2371 return (str - start);
2372 } else if (str[0] == ':' ||
2373 str[0] == CLOSE_PAREN ||
2374 str[0] == CLOSE_BRACE) {
2375 len = str - (start + 2);
2377 if (var[len] == '\0' && strncmp(var, start + 2, len) == 0) {
2378 return (0); /* match */
2381 * Not the variable we want to
2384 return (str - start);
2390 return (str - start);
2392 /* Single letter variable name */
2393 if (var[1] == '\0' && var[0] == str[0]) {
2394 return (0); /* match */
2396 str++; /* consume variable name */
2397 return (str - start);
2403 Var_SubstOnly(const char *var, const char *str, GNode *ctxt, Boolean err)
2405 Boolean errorReported;
2406 Buffer *buf; /* Buffer for forming things */
2409 * Set TRUE if an error has already been reported to prevent a
2410 * plethora of messages when recursing. XXXHB this comment sounds
2413 errorReported = FALSE;
2416 while (str[0] != '\0') {
2417 if (str[0] == '$') {
2420 skip = match_var(str, var);
2422 Buf_AddBytes(buf, skip, str);
2425 /* Variable invocation. */
2436 rval = VarParse(&subvp, &rfree);
2439 * When we get down here, rval should either
2440 * point to the value of this variable, or be
2443 if (rval == var_Error || rval == varNoError) {
2445 * If performing old-time variable
2446 * substitution, skip over the
2447 * variable and continue with the
2448 * substitution. Otherwise, store the
2449 * dollar sign and advance str so we
2450 * continue with the string...
2456 * If variable is undefined,
2457 * complain and skip the
2458 * variable. The complaint
2459 * will stop us from doing
2460 * anything when the file is
2463 if (!errorReported) {
2464 Parse_Error(PARSE_FATAL,
2465 "Undefined variable \"%.*s\"", subvp.ptr - subvp.input, str);
2467 errorReported = TRUE;
2470 Buf_AddByte(buf, (Byte)str[0]);
2475 * Copy all the characters from the
2476 * variable value straight into the
2479 Buf_Append(buf, rval);
2487 Buf_AddByte(buf, (Byte)str[0]);
2496 *-----------------------------------------------------------------------
2498 * Initialize the module
2504 * The VAR_CMD and VAR_GLOBAL contexts are created
2505 *-----------------------------------------------------------------------
2508 Var_Init(char **env)
2512 VAR_CMD = Targ_NewGN("Command");
2513 VAR_ENV = Targ_NewGN("Environment");
2514 VAR_GLOBAL = Targ_NewGN("Global");
2517 * Copy user environment variables into ENV context.
2519 for (ptr = env; *ptr != NULL; ++ptr) {
2520 char *tmp = estrdup(*ptr);
2521 const char *name = tmp;
2522 char *sep = strchr(name, '=');
2523 const char *value = sep + 1;
2527 VarAdd(name, value, VAR_ENV);
2534 *-----------------------------------------------------------------------
2536 * print all variables in a context
2537 *-----------------------------------------------------------------------
2545 printf("#*** Global Variables:\n");
2546 LST_FOREACH(ln, &VAR_GLOBAL->context) {
2548 printf("%-16s = %s\n", v->name, Buf_Data(v->val));
2551 printf("#*** Command-line Variables:\n");
2552 LST_FOREACH(ln, &VAR_CMD->context) {
2554 printf("%-16s = %s\n", v->name, Buf_Data(v->val));