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.
91 #include <sys/types.h>
110 typedef struct VarParser {
111 const char *const input; /* pointer to input string */
112 const char *ptr; /* current parser pos in input str */
119 char *name; /* the variable's name */
120 struct Buffer *val; /* its value */
121 int flags; /* miscellaneous status flags */
123 #define VAR_IN_USE 1 /* Variable's value currently being used.
124 * Used to avoid recursion */
126 #define VAR_JUNK 4 /* Variable is a junk variable that
127 * should be destroyed when done with
128 * it. Used by Var_Parse for undefined,
129 * modified variables */
131 #define VAR_TO_ENV 8 /* Place variable in environment */
135 struct Buffer *lhs; /* String to match */
136 struct Buffer *rhs; /* Replacement string (w/ &'s removed) */
143 #define VAR_SUB_GLOBAL 0x01 /* Apply substitution globally */
144 #define VAR_SUB_ONE 0x02 /* Apply substitution to one word */
145 #define VAR_SUB_MATCHED 0x04 /* There was a match */
146 #define VAR_MATCH_START 0x08 /* Match at start of word */
147 #define VAR_MATCH_END 0x10 /* Match at end of word */
150 typedef Boolean VarModifyProc(const char *, Boolean, struct Buffer *, void *);
152 static char *VarParse(VarParser *, Boolean *);
155 * This is a harmless return value for Var_Parse that can be used by Var_Subst
156 * to determine if there was an error in parsing -- easier than returning
157 * a flag, as things outside this module don't give a hoot.
159 char var_Error[] = "";
162 * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
163 * set false. Why not just use a constant? Well, gcc likes to condense
164 * identical string instances...
166 static char varNoError[] = "";
169 * Internally, variables are contained in four different contexts.
170 * 1) the environment. They may not be changed. If an environment
171 * variable is appended-to, the result is placed in the global
173 * 2) the global context. Variables set in the Makefile are located in
174 * the global context. It is the penultimate context searched when
176 * 3) the command-line context. All variables set on the command line
177 * are placed in this context. They are UNALTERABLE once placed here.
178 * 4) the local context. Each target has associated with it a context
179 * list. On this list are located the structures describing such
180 * local variables as $(@) and $(*)
181 * The four contexts are searched in the reverse order from which they are
184 static GNode *VAR_ENV; /* variables from the environment */
185 GNode *VAR_GLOBAL; /* variables from the makefile */
186 GNode *VAR_CMD; /* variables defined on the command-line */
188 Boolean oldVars; /* variable substitution style */
189 Boolean checkEnvFirst; /* -e flag */
191 #define OPEN_PAREN '('
192 #define CLOSE_PAREN ')'
193 #define OPEN_BRACE '{'
194 #define CLOSE_BRACE '}'
197 * Create a Var object.
200 * name Name of variable (copied).
201 * value Value of variable (copied) or NULL.
202 * flags Flags set on variable.
208 VarCreate(const char name[], const char value[], int flags)
212 v = emalloc(sizeof(Var));
213 v->name = estrdup(name);
214 v->val = Buf_Init(0);
218 Buf_Append(v->val, value);
224 * Destroy a Var object.
227 * v Object to destroy.
228 * f True if internal buffer in Buffer object is to be removed.
231 VarDestroy(Var *v, Boolean f)
234 Buf_Destroy(v->val, f);
240 * Remove the tail of the given word and place the result in the given
244 * TRUE if characters were added to the buffer (a space needs to be
245 * added to the buffer before the next word).
248 * The trimmed word is added to the buffer.
251 VarHead(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
255 slash = strrchr(word, '/');
258 Buf_AddByte(buf, (Byte)' ');
260 Buf_AppendRange(buf, word, slash);
263 * If no directory part, give . (q.v. the POSIX standard)
266 Buf_Append(buf, " .");
268 Buf_AddByte(buf, (Byte)'.');
275 * Remove the head of the given word and place the result in the given
279 * TRUE if characters were added to the buffer (a space needs to be
280 * added to the buffer before the next word).
283 * The trimmed word is added to the buffer.
286 VarTail(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
291 Buf_AddByte (buf, (Byte)' ');
294 slash = strrchr(word, '/');
297 Buf_Append(buf, slash);
299 Buf_Append(buf, word);
305 * Place the suffix of the given word in the given buffer.
308 * TRUE if characters were added to the buffer (a space needs to be
309 * added to the buffer before the next word).
312 * The suffix from the word is placed in the buffer.
315 VarSuffix(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
319 dot = strrchr(word, '.');
322 Buf_AddByte(buf, (Byte)' ');
325 Buf_Append(buf, dot);
332 * Remove the suffix of the given word and place the result in the
336 * TRUE if characters were added to the buffer (a space needs to be
337 * added to the buffer before the next word).
340 * The trimmed word is added to the buffer.
343 VarRoot(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
348 Buf_AddByte(buf, (Byte)' ');
351 dot = strrchr(word, '.');
353 Buf_AppendRange(buf, word, dot);
355 Buf_Append(buf, word);
361 * Place the word in the buffer if it matches the given pattern.
362 * Callback function for VarModify to implement the :M modifier.
363 * A space will be added if requested. A pattern is supplied
364 * which the word must match.
367 * TRUE if a space should be placed in the buffer before the next
371 * The word may be copied to the buffer.
374 VarMatch(const char *word, Boolean addSpace, Buffer *buf, void *pattern)
377 if (Str_Match(word, pattern)) {
379 Buf_AddByte(buf, (Byte)' ');
382 Buf_Append(buf, word);
389 * Place the word in the buffer if it matches the given pattern.
390 * Callback function for VarModify to implement the System V %
391 * modifiers. A space is added if requested.
394 * TRUE if a space should be placed in the buffer before the next
398 * The word may be copied to the buffer.
401 VarSYSVMatch(const char *word, Boolean addSpace, Buffer *buf, void *patp)
405 VarPattern *pat = (VarPattern *)patp;
408 Buf_AddByte(buf, (Byte)' ');
412 if ((ptr = Str_SYSVMatch(word, Buf_Data(pat->lhs), &len)) != NULL)
413 Str_SYSVSubst(buf, Buf_Data(pat->rhs), ptr, len);
415 Buf_Append(buf, word);
422 * Place the word in the buffer if it doesn't match the given pattern.
423 * Callback function for VarModify to implement the :N modifier. A
424 * space is added if requested.
427 * TRUE if a space should be placed in the buffer before the next
431 * The word may be copied to the buffer.
434 VarNoMatch(const char *word, Boolean addSpace, Buffer *buf, void *pattern)
437 if (!Str_Match(word, pattern)) {
439 Buf_AddByte(buf, (Byte)' ');
442 Buf_Append(buf, word);
448 * Perform a string-substitution on the given word, placing the
449 * result in the passed buffer. A space is added if requested.
452 * TRUE if a space is needed before more characters are added.
455 VarSubstitute(const char *word, Boolean addSpace, Buffer *buf, void *patternp)
457 size_t wordLen; /* Length of word */
458 const char *cp; /* General pointer */
459 VarPattern *pattern = patternp;
461 wordLen = strlen(word);
462 if (1) { /* substitute in each word of the variable */
464 * Break substitution down into simple anchored cases
465 * and if none of them fits, perform the general substitution
468 if ((pattern->flags & VAR_MATCH_START) &&
469 (strncmp(word, Buf_Data(pattern->lhs),
470 Buf_Size(pattern->lhs)) == 0)) {
472 * Anchored at start and beginning of word matches
475 if ((pattern->flags & VAR_MATCH_END) &&
476 (wordLen == Buf_Size(pattern->lhs))) {
478 * Also anchored at end and matches to the end
479 * (word is same length as pattern) add space
480 * and rhs only if rhs is non-null.
482 if (Buf_Size(pattern->rhs) != 0) {
484 Buf_AddByte(buf, (Byte)' ');
487 Buf_AppendBuf(buf, pattern->rhs);
490 } else if (pattern->flags & VAR_MATCH_END) {
492 * Doesn't match to end -- copy word wholesale
498 * Matches at start but need to copy in
499 * trailing characters.
501 if ((Buf_Size(pattern->rhs) + wordLen -
502 Buf_Size(pattern->lhs)) != 0) {
504 Buf_AddByte(buf, (Byte)' ');
508 Buf_AppendBuf(buf, pattern->rhs);
509 Buf_AddBytes(buf, wordLen -
510 Buf_Size(pattern->lhs),
511 (word + Buf_Size(pattern->lhs)));
514 } else if (pattern->flags & VAR_MATCH_START) {
516 * Had to match at start of word and didn't -- copy
521 } else if (pattern->flags & VAR_MATCH_END) {
523 * Anchored at end, Find only place match could occur
524 * (leftLen characters from the end of the word) and
525 * see if it does. Note that because the $ will be
526 * left at the end of the lhs, we have to use strncmp.
528 cp = word + (wordLen - Buf_Size(pattern->lhs));
529 if ((cp >= word) && (strncmp(cp, Buf_Data(pattern->lhs),
530 Buf_Size(pattern->lhs)) == 0)) {
532 * Match found. If we will place characters in
533 * the buffer, add a space before hand as
534 * indicated by addSpace, then stuff in the
535 * initial, unmatched part of the word followed
536 * by the right-hand-side.
538 if ((cp - word) + Buf_Size(pattern->rhs) != 0) {
540 Buf_AddByte(buf, (Byte)' ');
544 Buf_AppendRange(buf, word, cp);
545 Buf_AppendBuf(buf, pattern->rhs);
549 * Had to match at end and didn't. Copy entire
556 * Pattern is unanchored: search for the pattern in the
557 * word using strstr(3), copying unmatched portions and
558 * the right-hand-side for each match found, handling
559 * non-global substitutions correctly, etc. When the
560 * loop is done, any remaining part of the word (word
561 * and wordLen are adjusted accordingly through the
562 * loop) is copied straight into the buffer.
563 * addSpace is set FALSE as soon as a space is added
570 origSize = Buf_Size(buf);
572 cp = strstr(word, Buf_Data(pattern->lhs));
574 if (addSpace && (((cp - word) +
575 Buf_Size(pattern->rhs)) != 0)) {
576 Buf_AddByte(buf, (Byte)' ');
579 Buf_AppendRange(buf, word, cp);
580 Buf_AppendBuf(buf, pattern->rhs);
581 wordLen -= (cp - word) +
582 Buf_Size(pattern->lhs);
583 word = cp + Buf_Size(pattern->lhs);
584 if (wordLen == 0 || (pattern->flags &
585 VAR_SUB_GLOBAL) == 0) {
594 Buf_AddByte(buf, (Byte)' ');
596 Buf_AddBytes(buf, wordLen, (const Byte *)word);
600 * If added characters to the buffer, need to add a
601 * space before we add any more. If we didn't add any,
602 * just return the previous value of addSpace.
604 return ((Buf_Size(buf) != origSize) || addSpace);
607 * Common code for anchored substitutions:
608 * addSpace was set TRUE if characters were added to the buffer.
614 Buf_AddByte(buf, (Byte)' ');
616 Buf_AddBytes(buf, wordLen, (const Byte *)word);
621 * Print the error caused by a regcomp or regexec call.
624 * An error gets printed.
627 VarREError(int err, regex_t *pat, const char *str)
632 errlen = regerror(err, pat, 0, 0);
633 errbuf = emalloc(errlen);
634 regerror(err, pat, errbuf, errlen);
635 Error("%s: %s", str, errbuf);
641 * Perform a regex substitution on the given word, placing the
642 * result in the passed buffer. A space is added if requested.
645 * TRUE if a space is needed before more characters are added.
648 VarRESubstitute(const char *word, Boolean addSpace, Buffer *buf, void *patternp)
657 #define MAYBE_ADD_SPACE() \
658 if (addSpace && !added) \
659 Buf_AddByte(buf, (Byte)' '); \
666 if ((pat->flags & (VAR_SUB_ONE | VAR_SUB_MATCHED)) ==
667 (VAR_SUB_ONE | VAR_SUB_MATCHED)) {
671 xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
676 pat->flags |= VAR_SUB_MATCHED;
677 if (pat->matches[0].rm_so > 0) {
679 Buf_AddBytes(buf, pat->matches[0].rm_so,
683 for (rp = Buf_Data(pat->rhs); *rp; rp++) {
684 if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
686 Buf_AddByte(buf, (Byte)rp[1]);
689 } else if ((*rp == '&') ||
690 ((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
709 Error("No subexpression %s",
714 } else if ((pat->matches[n].rm_so == -1) &&
715 (pat->matches[n].rm_eo == -1)) {
716 Error("No match for subexpression %s",
722 subbuf = wp + pat->matches[n].rm_so;
723 sublen = pat->matches[n].rm_eo -
724 pat->matches[n].rm_so;
729 Buf_AddBytes(buf, sublen,
730 (const Byte *)subbuf);
734 Buf_AddByte(buf, (Byte)*rp);
737 wp += pat->matches[0].rm_eo;
738 if (pat->flags & VAR_SUB_GLOBAL) {
740 if (pat->matches[0].rm_so == 0 &&
741 pat->matches[0].rm_eo == 0) {
743 Buf_AddByte(buf, (Byte)*wp);
756 VarREError(xrv, &pat->re, "Unexpected regex error");
766 return (addSpace || added);
770 * Find a variable in a variable list.
773 VarLookup(Lst *vlist, const char *name)
777 LST_FOREACH(ln, vlist)
778 if (strcmp(((const Var *)Lst_Datum(ln))->name, name) == 0)
779 return (Lst_Datum(ln));
784 * Expand a variable name's embedded variables in the given context.
787 * The contents of name, possibly expanded.
790 VarPossiblyExpand(const char *name, GNode *ctxt)
794 if (strchr(name, '$') != NULL) {
795 buf = Var_Subst(name, ctxt, 0);
796 return (Buf_Peel(buf));
798 return estrdup(name);
803 * If the variable name begins with a '.', it could very well be
804 * one of the local ones. We check the name against all the local
805 * variables and substitute the short version in for 'name' if it
806 * matches one of them.
809 VarLocal(const char name[])
811 if (name[0] == '.') {
814 if (!strcmp(name, ".ALLSRC"))
816 if (!strcmp(name, ".ARCHIVE"))
820 if (!strcmp(name, ".IMPSRC"))
824 if (!strcmp(name, ".MEMBER"))
828 if (!strcmp(name, ".OODATE"))
832 if (!strcmp(name, ".PREFIX"))
836 if (!strcmp(name, ".TARGET"))
847 * Find the given variable in the given context and the enviornment.
850 * A pointer to the structure describing the desired variable or
851 * NULL if the variable does not exist.
854 VarFindEnv(const char name[], GNode *ctxt)
858 name = VarLocal(name);
860 if ((var = VarLookup(&ctxt->context, name)) != NULL)
863 if ((var = VarLookup(&VAR_ENV->context, name)) != NULL)
870 * Look for the variable in the given context.
873 VarFindOnly(const char name[], GNode *ctxt)
877 name = VarLocal(name);
879 if ((var = VarLookup(&ctxt->context, name)) != NULL)
886 * Look for the variable in all contexts.
889 VarFindAny(const char name[], GNode *ctxt)
891 Boolean localCheckEnvFirst;
895 name = VarLocal(name);
898 * Note whether this is one of the specific variables we were told
899 * through the -E flag to use environment-variable-override for.
901 localCheckEnvFirst = FALSE;
902 LST_FOREACH(ln, &envFirstVars) {
903 if (strcmp(Lst_Datum(ln), name) == 0) {
904 localCheckEnvFirst = TRUE;
910 * First look for the variable in the given context. If it's not there,
911 * look for it in VAR_CMD, VAR_GLOBAL and the environment,
912 * in that order, depending on the FIND_* flags in 'flags'
914 if ((var = VarLookup(&ctxt->context, name)) != NULL)
917 /* not there - try command line context */
918 if (ctxt != VAR_CMD) {
919 if ((var = VarLookup(&VAR_CMD->context, name)) != NULL)
923 /* not there - try global context, but only if not -e/-E */
924 if (ctxt != VAR_GLOBAL && (!checkEnvFirst && !localCheckEnvFirst)) {
925 if ((var = VarLookup(&VAR_GLOBAL->context, name)) != NULL)
929 if ((var = VarLookup(&VAR_ENV->context, name)) != NULL)
932 /* deferred check for the environment (in case of -e/-E) */
933 if ((ctxt != VAR_GLOBAL) && (checkEnvFirst || localCheckEnvFirst)) {
934 if ((var = VarLookup(&VAR_GLOBAL->context, name)) != NULL)
942 * Add a new variable of name name and value val to the given context.
945 * The new variable is placed at the front of the given context
946 * The name and val arguments are duplicated so they may
950 VarAdd(const char *name, const char *val, GNode *ctxt)
954 Lst_AtFront(&ctxt->context, v = VarCreate(name, val, 0));
955 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
960 * Remove a variable from a context.
963 * The Var structure is removed and freed.
966 Var_Delete(const char *name, GNode *ctxt)
970 DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
971 LST_FOREACH(ln, &ctxt->context) {
972 if (strcmp(((const Var *)Lst_Datum(ln))->name, name) == 0) {
973 VarDestroy(Lst_Datum(ln), TRUE);
974 Lst_Remove(&ctxt->context, ln);
981 * Set the variable name to the value val in the given context.
984 * If the variable doesn't yet exist, a new record is created for it.
985 * Else the old value is freed and the new one stuck in its place
988 * The variable is searched for only in its context before being
989 * created in that context. I.e. if the context is VAR_GLOBAL,
990 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
991 * VAR_CMD->context is searched. This is done to avoid the literally
992 * thousands of unnecessary strcmp's that used to be done to
993 * set, say, $(@) or $(<).
996 Var_Set(const char *name, const char *val, GNode *ctxt)
1002 * We only look for a variable in the given context since anything
1003 * set here will override anything in a lower context, so there's not
1004 * much point in searching them all just to save a bit of memory...
1006 n = VarPossiblyExpand(name, ctxt);
1007 v = VarFindOnly(n, ctxt);
1009 v = VarAdd(n, val, ctxt);
1012 Buf_Append(v->val, val);
1013 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, val));
1016 if (ctxt == VAR_CMD || (v->flags & VAR_TO_ENV)) {
1018 * Any variables given on the command line
1019 * are automatically exported to the
1020 * environment (as per POSIX standard)
1029 * Set the a global name variable to the value.
1032 Var_SetGlobal(const char name[], const char value[])
1035 Var_Set(name, value, VAR_GLOBAL);
1040 * Set the VAR_TO_ENV flag on a variable
1043 Var_SetEnv(const char *name, GNode *ctxt)
1047 v = VarFindOnly(name, VAR_CMD);
1050 * Do not allow .EXPORT: to be set on variables
1051 * from the comand line or MAKEFLAGS.
1054 "Warning: Did not set .EXPORTVAR: on %s because it "
1055 "is from the comand line or MAKEFLAGS", name);
1059 v = VarFindAny(name, ctxt);
1061 Lst_AtFront(&VAR_ENV->context,
1062 VarCreate(name, NULL, VAR_TO_ENV));
1063 setenv(name, "", 1);
1064 Error("Warning: .EXPORTVAR: set on undefined variable %s", name);
1066 if ((v->flags & VAR_TO_ENV) == 0) {
1067 v->flags |= VAR_TO_ENV;
1068 setenv(v->name, Buf_Data(v->val), 1);
1074 * The variable of the given name has the given value appended to it in
1075 * the given context.
1078 * If the variable doesn't exist, it is created. Else the strings
1079 * are concatenated (with a space in between).
1082 * Only if the variable is being sought in the global context is the
1083 * environment searched.
1084 * XXX: Knows its calling circumstances in that if called with ctxt
1085 * an actual target, it will only search that context since only
1086 * a local variable could be being appended to. This is actually
1087 * a big win and must be tolerated.
1090 Var_Append(const char *name, const char *val, GNode *ctxt)
1095 n = VarPossiblyExpand(name, ctxt);
1096 if (ctxt == VAR_GLOBAL) {
1097 v = VarFindEnv(n, ctxt);
1099 v = VarFindOnly(n, ctxt);
1102 VarAdd(n, val, ctxt);
1104 Buf_AddByte(v->val, (Byte)' ');
1105 Buf_Append(v->val, val);
1106 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, Buf_Data(v->val)));
1112 * See if the given variable exists.
1115 * TRUE if it does, FALSE if it doesn't
1118 Var_Exists(const char *name, GNode *ctxt)
1123 n = VarPossiblyExpand(name, ctxt);
1124 v = VarFindAny(n, ctxt);
1135 * Return the value of the named variable in the given context
1138 * The value if the variable exists, NULL if it doesn't.
1141 Var_Value(const char name[], GNode *ctxt)
1146 n = VarPossiblyExpand(name, ctxt);
1147 v = VarFindAny(n, ctxt);
1152 return (Buf_Data(v->val));
1157 * Modify each of the words of the passed string using the given
1158 * function. Used to implement all modifiers.
1161 * A string of all the words modified appropriately.
1164 * Uses brk_string() so it invalidates any previous call to
1168 VarModify(const char *str, VarModifyProc *modProc, void *datum)
1171 Buffer *buf; /* Buffer for the new string */
1173 Boolean addSpace; /*
1174 * TRUE if need to add a space to
1175 * the buffer before adding the
1179 brk_string(&aa, str, FALSE);
1183 for (i = 1; i < aa.argc; i++)
1184 addSpace = (*modProc)(aa.argv[i], addSpace, buf, datum);
1187 return (Buf_Peel(buf));
1191 * Sort the words in the string.
1194 * str String whose words should be sorted
1195 * cmp A comparison function to control the ordering
1198 * A string containing the words sorted
1201 VarSortWords(const char *str, int (*cmp)(const void *, const void *))
1207 brk_string(&aa, str, FALSE);
1208 qsort(aa.argv + 1, aa.argc - 1, sizeof(char *), cmp);
1211 for (i = 1; i < aa.argc; i++) {
1212 Buf_Append(buf, aa.argv[i]);
1213 Buf_AddByte(buf, (Byte)((i < aa.argc - 1) ? ' ' : '\0'));
1217 return (Buf_Peel(buf));
1221 SortIncreasing(const void *l, const void *r)
1224 return (strcmp(*(const char* const*)l, *(const char* const*)r));
1228 * Remove adjacent duplicate words.
1231 * A string containing the resulting words.
1234 VarUniq(const char *str)
1237 Buffer *buf; /* Buffer for new string */
1241 brk_string(&aa, str, FALSE);
1244 for (j = 1, i = 2; i < aa.argc; i++) {
1245 if (strcmp(aa.argv[i], aa.argv[j]) != 0 && (++j != i))
1246 aa.argv[j] = aa.argv[i];
1251 for (i = 1; i < aa.argc; i++) {
1252 Buf_AddBytes(buf, strlen(aa.argv[i]), (Byte *)aa.argv[i]);
1253 if (i != aa.argc - 1)
1254 Buf_AddByte(buf, ' ');
1256 Buf_AddByte(buf, '\0');
1259 return (Buf_Peel(buf));
1263 * Pass through the tstr looking for 1) escaped delimiters,
1264 * '$'s and backslashes (place the escaped character in
1265 * uninterpreted) and 2) unescaped $'s that aren't before
1266 * the delimiter (expand the variable substitution).
1267 * Return the expanded string or NULL if the delimiter was missing
1268 * If pattern is specified, handle escaped ampersands, and replace
1269 * unescaped ampersands with the lhs of the pattern.
1272 * A string of all the words modified appropriately.
1273 * If length is specified, return the string length of the buffer
1274 * If flags is specified and the last character of the pattern is a
1275 * $ set the VAR_MATCH_END bit of flags.
1278 VarGetPattern(VarParser *vp, int delim, int *flags, VarPattern *patt)
1285 * Skim through until the matching delimiter is found; pick up
1286 * variable substitutions on the way. Also allow backslashes to quote
1287 * the delimiter, $, and \, but don't touch other backslashes.
1289 while (*vp->ptr != '\0') {
1290 if (*vp->ptr == delim) {
1293 } else if ((vp->ptr[0] == '\\') &&
1294 ((vp->ptr[1] == delim) ||
1295 (vp->ptr[1] == '\\') ||
1296 (vp->ptr[1] == '$') ||
1297 (vp->ptr[1] == '&' && patt != NULL))) {
1298 vp->ptr++; /* consume backslash */
1299 Buf_AddByte(buf, (Byte)vp->ptr[0]);
1302 } else if (vp->ptr[0] == '$') {
1303 if (vp->ptr[1] == delim) {
1304 if (flags == NULL) {
1305 Buf_AddByte(buf, (Byte)vp->ptr[0]);
1309 * Unescaped $ at end of patt =>
1310 * anchor patt at end.
1312 *flags |= VAR_MATCH_END;
1327 * If unescaped dollar sign not
1328 * before the delimiter, assume it's
1329 * a variable substitution and
1332 rval = VarParse(&subvp, &rfree);
1333 Buf_Append(buf, rval);
1336 vp->ptr = subvp.ptr;
1338 } else if (vp->ptr[0] == '&' && patt != NULL) {
1339 Buf_AppendBuf(buf, patt->lhs);
1342 Buf_AddByte(buf, (Byte)vp->ptr[0]);
1347 Buf_Destroy(buf, TRUE);
1352 * Make sure this variable is fully expanded.
1355 VarExpand(Var *v, VarParser *vp)
1360 if (v->flags & VAR_IN_USE) {
1361 Fatal("Variable %s is recursive.", v->name);
1365 v->flags |= VAR_IN_USE;
1368 * Before doing any modification, we have to make sure the
1369 * value has been fully expanded. If it looks like recursion
1370 * might be necessary (there's a dollar sign somewhere in the
1371 * variable's value) we just call Var_Subst to do any other
1372 * substitutions that are necessary. Note that the value
1373 * returned by Var_Subst will have been
1374 * dynamically-allocated, so it will need freeing when we
1377 value = Buf_Data(v->val);
1378 if (strchr(value, '$') == NULL) {
1379 result = strdup(value);
1383 buf = Var_Subst(value, vp->ctxt, vp->err);
1384 result = Buf_Peel(buf);
1387 v->flags &= ~VAR_IN_USE;
1393 * Select only those words in value that match the modifier.
1396 modifier_M(VarParser *vp, const char value[], char endc)
1403 modifier = vp->ptr[0];
1404 vp->ptr++; /* consume 'M' or 'N' */
1407 * Compress the \:'s out of the pattern, so allocate enough
1408 * room to hold the uncompressed pattern and compress the
1409 * pattern into that space.
1411 patt = estrdup(vp->ptr);
1413 while (vp->ptr[0] != '\0') {
1414 if (vp->ptr[0] == endc || vp->ptr[0] == ':') {
1417 if (vp->ptr[0] == '\\' &&
1418 (vp->ptr[1] == endc || vp->ptr[1] == ':')) {
1419 vp->ptr++; /* consume backslash */
1426 DEBUGF(VAR, ("Pattern :%s\n", patt));
1428 if (modifier == 'M') {
1429 newValue = VarModify(value, VarMatch, patt);
1431 newValue = VarModify(value, VarNoMatch, patt);
1439 * Substitute the replacement string for the pattern. The substitution
1440 * is applied to each word in value.
1443 modifier_S(VarParser *vp, const char value[], Var *v)
1451 vp->ptr++; /* consume 'S' */
1453 delim = *vp->ptr; /* used to find end of pattern */
1454 vp->ptr++; /* consume 1st delim */
1457 * If pattern begins with '^', it is anchored to the start of the
1458 * word -- skip over it and flag pattern.
1460 if (*vp->ptr == '^') {
1461 patt.flags |= VAR_MATCH_START;
1465 patt.lhs = VarGetPattern(vp, delim, &patt.flags, NULL);
1466 if (patt.lhs == NULL) {
1468 * LHS didn't end with the delim, complain and exit.
1470 Fatal("Unclosed substitution for %s (%c missing)",
1474 vp->ptr++; /* consume 2nd delim */
1476 patt.rhs = VarGetPattern(vp, delim, NULL, &patt);
1477 if (patt.rhs == NULL) {
1479 * RHS didn't end with the delim, complain and exit.
1481 Fatal("Unclosed substitution for %s (%c missing)",
1485 vp->ptr++; /* consume last delim */
1488 * Check for global substitution. If 'g' after the final delimiter,
1489 * substitution is global and is marked that way.
1491 if (vp->ptr[0] == 'g') {
1492 patt.flags |= VAR_SUB_GLOBAL;
1497 * Global substitution of the empty string causes an infinite number
1498 * of matches, unless anchored by '^' (start of string) or '$' (end
1499 * of string). Catch the infinite substitution here. Note that flags
1500 * can only contain the 3 bits we're interested in so we don't have
1501 * to mask unrelated bits. We can test for equality.
1503 if (Buf_Size(patt.lhs) == 0 && patt.flags == VAR_SUB_GLOBAL)
1504 Fatal("Global substitution of the empty string");
1506 newValue = VarModify(value, VarSubstitute, &patt);
1509 * Free the two strings.
1518 modifier_C(VarParser *vp, char value[], Var *v)
1527 vp->ptr++; /* consume 'C' */
1529 delim = *vp->ptr; /* delimiter between sections */
1531 vp->ptr++; /* consume 1st delim */
1533 patt.lhs = VarGetPattern(vp, delim, NULL, NULL);
1534 if (patt.lhs == NULL) {
1535 Fatal("Unclosed substitution for %s (%c missing)",
1539 vp->ptr++; /* consume 2st delim */
1541 patt.rhs = VarGetPattern(vp, delim, NULL, NULL);
1542 if (patt.rhs == NULL) {
1543 Fatal("Unclosed substitution for %s (%c missing)",
1547 vp->ptr++; /* consume last delim */
1551 patt.flags |= VAR_SUB_GLOBAL;
1552 vp->ptr++; /* consume 'g' */
1555 patt.flags |= VAR_SUB_ONE;
1556 vp->ptr++; /* consume '1' */
1562 error = regcomp(&patt.re, Buf_Data(patt.lhs), REG_EXTENDED);
1564 VarREError(error, &patt.re, "RE substitution error");
1570 patt.nsub = patt.re.re_nsub + 1;
1575 patt.matches = emalloc(patt.nsub * sizeof(regmatch_t));
1577 newValue = VarModify(value, VarRESubstitute, &patt);
1588 sysVvarsub(VarParser *vp, char startc, Var *v, const char value[])
1592 * This can either be a bogus modifier or a System-V substitution
1602 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1607 * First we make a pass through the string trying to verify it is a
1608 * SYSV-make-style translation: it must be: <string1>=<string2>)
1613 while (*cp != '\0' && cnt) {
1616 /* continue looking for endc */
1617 } else if (*cp == endc)
1619 else if (*cp == startc)
1625 if (*cp == endc && eqFound) {
1627 * Now we break this sucker into the lhs and rhs.
1629 patt.lhs = VarGetPattern(vp, '=', &patt.flags, NULL);
1630 if (patt.lhs == NULL) {
1631 Fatal("Unclosed substitution for %s (%c missing)",
1634 vp->ptr++; /* consume '=' */
1636 patt.rhs = VarGetPattern(vp, endc, NULL, &patt);
1637 if (patt.rhs == NULL) {
1638 Fatal("Unclosed substitution for %s (%c missing)",
1643 * SYSV modifications happen through the whole string. Note
1644 * the pattern is anchored at the end.
1646 newStr = VarModify(value, VarSYSVMatch, &patt);
1653 Error("Unknown modifier '%c'\n", *vp->ptr);
1655 while (*vp->ptr != '\0') {
1656 if (*vp->ptr == endc && *vp->ptr == ':') {
1668 * Quote shell meta-characters in the string
1674 Var_Quote(const char *str)
1677 /* This should cover most shells :-( */
1678 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
1680 buf = Buf_Init(MAKE_BSIZE);
1681 for (; *str; str++) {
1682 if (strchr(meta, *str) != NULL)
1683 Buf_AddByte(buf, (Byte)'\\');
1684 Buf_AddByte(buf, (Byte)*str);
1687 return (Buf_Peel(buf));
1692 * Now we need to apply any modifiers the user wants applied.
1695 * words which match the given <pattern>.
1696 * <pattern> is of the standard file
1699 * words which do not match the given <pattern>
1700 * <pattern> is of the standard file
1702 * :S<d><pat1><d><pat2><d>[g]
1703 * Substitute <pat2> for <pat1> in the value
1704 * :C<d><pat1><d><pat2><d>[g]
1705 * Substitute <pat2> for regex <pat1> in the value
1706 * :H Substitute the head of each word
1707 * :T Substitute the tail of each word
1708 * :E Substitute the extension (minus '.') of
1710 * :R Substitute the root of each word
1711 * (pathname minus the suffix).
1713 * Like :S, but the rhs goes to the end of
1715 * :U Converts variable to upper-case.
1716 * :L Converts variable to lower-case.
1717 * :O ("Order") Alphabeticaly sort words in variable.
1718 * :u ("uniq") Remove adjacent duplicate words.
1721 ParseModifier(VarParser *vp, char startc, Var *v, Boolean *freeResult)
1726 value = VarExpand(v, vp);
1729 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1731 vp->ptr++; /* consume first colon */
1733 while (*vp->ptr != '\0') {
1734 char *newStr; /* New value to return */
1736 if (*vp->ptr == endc) {
1740 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *vp->ptr, value));
1744 newStr = modifier_M(vp, value, endc);
1747 newStr = modifier_S(vp, value, v);
1750 newStr = modifier_C(vp, value, v);
1753 /* :tl :tu for OSF ODE & NetBSD make compatibility */
1754 switch (vp->ptr[1]) {
1766 if (vp->ptr[1] != endc && vp->ptr[1] != ':') {
1768 if ((vp->ptr[0] == 's') &&
1769 (vp->ptr[1] == 'h') &&
1770 (vp->ptr[2] == endc || vp->ptr[2] == ':')) {
1775 Cmd_Exec(value, &error));
1777 newStr = estrdup("");
1781 Error(error, value);
1786 newStr = sysVvarsub(vp, startc, v, value);
1791 switch (vp->ptr[0]) {
1797 buf = Buf_Init(MAKE_BSIZE);
1798 for (cp = value; *cp; cp++)
1799 Buf_AddByte(buf, (Byte)tolower(*cp));
1801 newStr = Buf_Peel(buf);
1807 newStr = VarSortWords(value, SortIncreasing);
1811 newStr = Var_Quote(value);
1815 newStr = VarModify(value, VarTail, NULL);
1823 buf = Buf_Init(MAKE_BSIZE);
1824 for (cp = value; *cp; cp++)
1825 Buf_AddByte(buf, (Byte)toupper(*cp));
1827 newStr = Buf_Peel(buf);
1833 newStr = VarModify(value, VarHead, NULL);
1837 newStr = VarModify(value, VarSuffix, NULL);
1841 newStr = VarModify(value, VarRoot, NULL);
1845 newStr = VarUniq(value);
1849 newStr = sysVvarsub(vp, startc, v, value);
1855 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1861 *freeResult = (value == var_Error) ? FALSE : TRUE;
1863 if (vp->ptr[0] == ':') {
1864 vp->ptr++; /* consume colon */
1872 ParseRestModifier(VarParser *vp, char startc, Buffer *buf, Boolean *freeResult)
1879 vname = Buf_GetAll(buf, &vlen);
1881 v = VarFindAny(vname, vp->ctxt);
1883 value = ParseModifier(vp, startc, v, freeResult);
1887 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1890 * Still need to get to the end of the variable
1891 * specification, so kludge up a Var structure for the
1894 v = VarCreate(vname, NULL, VAR_JUNK);
1895 value = ParseModifier(vp, startc, v, freeResult);
1899 VarDestroy(v, TRUE);
1901 consumed = vp->ptr - vp->input + 1;
1903 * If substituting a local variable in a non-local context,
1904 * assume it's for dynamic source stuff. We have to handle
1905 * this specially and return the longhand for the variable
1906 * with the dollar sign escaped so it makes it back to the
1907 * caller. Only four of the local variables are treated
1908 * specially as they are the only four that will be set when
1909 * dynamic sources are expanded.
1912 (vlen == 2 && (vname[1] == 'F' || vname[1] == 'D'))) {
1913 if (strchr("!%*@", vname[0]) != NULL) {
1914 value = emalloc(consumed + 1);
1915 strncpy(value, vp->input, consumed);
1916 value[consumed] = '\0';
1924 isupper((unsigned char)vname[1])) {
1925 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1926 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1927 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1928 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1929 value = emalloc(consumed + 1);
1930 strncpy(value, vp->input, consumed);
1931 value[consumed] = '\0';
1938 *freeResult = FALSE;
1939 return (vp->err ? var_Error : varNoError);
1942 * Check for D and F forms of local variables since we're in
1943 * a local context and the name is the right length.
1946 (vname[1] == 'F' || vname[1] == 'D') &&
1947 (strchr("!%*<>@", vname[0]) != NULL)) {
1953 v = VarFindOnly(name, vp->ctxt);
1955 value = ParseModifier(vp, startc, v, freeResult);
1961 * Still need to get to the end of the variable
1962 * specification, so kludge up a Var structure for the
1965 v = VarCreate(vname, NULL, VAR_JUNK);
1966 value = ParseModifier(vp, startc, v, freeResult);
1970 VarDestroy(v, TRUE);
1972 *freeResult = FALSE;
1973 return (vp->err ? var_Error : varNoError);
1978 ParseRestEnd(VarParser *vp, Buffer *buf, Boolean *freeResult)
1985 vname = Buf_GetAll(buf, &vlen);
1987 v = VarFindAny(vname, vp->ctxt);
1989 value = VarExpand(v, vp);
1994 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1995 size_t consumed = vp->ptr - vp->input + 1;
1998 * If substituting a local variable in a non-local context,
1999 * assume it's for dynamic source stuff. We have to handle
2000 * this specially and return the longhand for the variable
2001 * with the dollar sign escaped so it makes it back to the
2002 * caller. Only four of the local variables are treated
2003 * specially as they are the only four that will be set when
2004 * dynamic sources are expanded.
2007 (vlen == 2 && (vname[1] == 'F' || vname[1] == 'D'))) {
2008 if (strchr("!%*@", vname[0]) != NULL) {
2009 value = emalloc(consumed + 1);
2010 strncpy(value, vp->input, consumed);
2011 value[consumed] = '\0';
2019 isupper((unsigned char)vname[1])) {
2020 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
2021 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
2022 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
2023 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
2024 value = emalloc(consumed + 1);
2025 strncpy(value, vp->input, consumed);
2026 value[consumed] = '\0';
2034 * Check for D and F forms of local variables since we're in
2035 * a local context and the name is the right length.
2038 (vname[1] == 'F' || vname[1] == 'D') &&
2039 (strchr("!%*<>@", vname[0]) != NULL)) {
2045 v = VarFindOnly(name, vp->ctxt);
2049 * No need for nested expansion or anything,
2050 * as we're the only one who sets these
2051 * things and we sure don't put nested
2052 * invocations in them...
2054 val = Buf_Data(v->val);
2056 if (vname[1] == 'D') {
2057 val = VarModify(val, VarHead, NULL);
2059 val = VarModify(val, VarTail, NULL);
2068 *freeResult = FALSE;
2069 return (vp->err ? var_Error : varNoError);
2073 * Parse a multi letter variable name, and return it's value.
2076 VarParseLong(VarParser *vp, Boolean *freeResult)
2083 buf = Buf_Init(MAKE_BSIZE);
2085 startc = vp->ptr[0];
2086 vp->ptr++; /* consume opening paren or brace */
2088 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
2091 * Process characters until we reach an end character or a colon,
2092 * replacing embedded variables as we go.
2094 while (*vp->ptr != '\0') {
2095 if (*vp->ptr == endc) {
2096 value = ParseRestEnd(vp, buf, freeResult);
2097 vp->ptr++; /* consume closing paren or brace */
2098 Buf_Destroy(buf, TRUE);
2101 } else if (*vp->ptr == ':') {
2102 value = ParseRestModifier(vp, startc, buf, freeResult);
2103 vp->ptr++; /* consume closing paren or brace */
2104 Buf_Destroy(buf, TRUE);
2107 } else if (*vp->ptr == '$') {
2118 rval = VarParse(&subvp, &rfree);
2119 if (rval == var_Error) {
2120 Fatal("Error expanding embedded variable.");
2122 Buf_Append(buf, rval);
2125 vp->ptr = subvp.ptr;
2127 Buf_AddByte(buf, (Byte)*vp->ptr);
2132 /* If we did not find the end character, return var_Error */
2133 Buf_Destroy(buf, TRUE);
2134 *freeResult = FALSE;
2139 * Parse a single letter variable name, and return it's value.
2142 VarParseShort(VarParser *vp, Boolean *freeResult)
2148 vname[0] = vp->ptr[0];
2151 vp->ptr++; /* consume single letter */
2153 v = VarFindAny(vname, vp->ctxt);
2155 value = VarExpand(v, vp);
2161 * If substituting a local variable in a non-local context, assume
2162 * it's for dynamic source stuff. We have to handle this specially
2163 * and return the longhand for the variable with the dollar sign
2164 * escaped so it makes it back to the caller. Only four of the local
2165 * variables are treated specially as they are the only four that
2166 * will be set when dynamic sources are expanded.
2168 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
2170 /* XXX: It looks like $% and $! are reversed here */
2174 return (estrdup("$(.TARGET)"));
2177 return (estrdup("$(.ARCHIVE)"));
2180 return (estrdup("$(.PREFIX)"));
2183 return (estrdup("$(.MEMBER)"));
2185 *freeResult = FALSE;
2186 return (vp->err ? var_Error : varNoError);
2190 /* Variable name was not found. */
2191 *freeResult = FALSE;
2192 return (vp->err ? var_Error : varNoError);
2196 VarParse(VarParser *vp, Boolean *freeResult)
2199 vp->ptr++; /* consume '$' or last letter of conditional */
2201 if (vp->ptr[0] == '\0') {
2202 /* Error, there is only a dollar sign in the input string. */
2203 *freeResult = FALSE;
2204 return (vp->err ? var_Error : varNoError);
2206 } else if (vp->ptr[0] == OPEN_PAREN || vp->ptr[0] == OPEN_BRACE) {
2207 /* multi letter variable name */
2208 return (VarParseLong(vp, freeResult));
2211 /* single letter variable name */
2212 return (VarParseShort(vp, freeResult));
2217 * Given the start of a variable invocation, extract the variable
2218 * name and find its value, then modify it according to the
2222 * The value of the variable or var_Error if the specification
2223 * is invalid. The number of characters in the specification
2224 * is placed in the variable pointed to by consumed. (for
2225 * invalid specifications, this is just 2 to skip the '$' and
2226 * the following letter, or 1 if '$' was the last character
2227 * in the string). A Boolean in *freeResult telling whether the
2228 * returned string should be freed by the caller.
2231 Var_Parse(const char input[], GNode *ctxt, Boolean err,
2232 size_t *consumed, Boolean *freeResult)
2243 value = VarParse(&vp, freeResult);
2244 *consumed += vp.ptr - vp.input;
2249 * Given the start of a variable invocation, determine the length
2250 * of the specification.
2253 * The number of characters in the specification. For invalid
2254 * specifications, this is just 2 to skip the '$' and the
2255 * following letter, or 1 if '$' was the last character in the
2259 Var_Match(const char input[], GNode *ctxt)
2271 value = VarParse(&vp, &freeResult);
2275 return (vp.ptr - vp.input);
2279 match_var(const char str[], const char var[])
2281 const char *start = str;
2284 str++; /* consume '$' */
2286 if (str[0] == OPEN_PAREN || str[0] == OPEN_BRACE) {
2287 str++; /* consume opening paren or brace */
2289 while (str[0] != '\0') {
2290 if (str[0] == '$') {
2292 * A variable inside the variable. We cannot
2293 * expand the external variable yet.
2295 return (str - start);
2296 } else if (str[0] == ':' ||
2297 str[0] == CLOSE_PAREN ||
2298 str[0] == CLOSE_BRACE) {
2299 len = str - (start + 2);
2301 if (strncmp(var, start + 2, len) == 0 && var[len] == '\0') {
2302 return (0); /* match */
2305 * Not the variable we want to
2308 return (str - start);
2314 return (str - start);
2316 /* Single letter variable name */
2317 if (var[1] == '\0' && var[0] == str[0]) {
2318 return (0); /* match */
2320 str++; /* consume variable name */
2321 return (str - start);
2327 * Substitute for all variables in the given string in the given
2328 * context If err is TRUE, Parse_Error will be called when an
2329 * undefined variable is encountered.
2332 * The resulting string.
2335 * None. The old string must be freed by the caller
2338 Var_Subst(const char *str, GNode *ctxt, Boolean err)
2340 Boolean errorReported;
2341 Buffer *buf; /* Buffer for forming things */
2344 * Set TRUE if an error has already been reported to prevent a
2345 * plethora of messages when recursing. XXXHB this comment sounds
2348 errorReported = FALSE;
2351 while (str[0] != '\0') {
2352 if ((str[0] == '$') && (str[1] == '$')) {
2354 * A dollar sign may be escaped with another dollar
2355 * sign. In such a case, we skip over the escape
2356 * character and store the dollar sign into the
2360 Buf_AddByte(buf, (Byte)str[0]);
2363 } else if (str[0] == '$') {
2364 /* Variable invocation. */
2375 rval = VarParse(&subvp, &rfree);
2378 * When we come down here, val should either point to
2379 * the value of this variable, suitably modified, or
2380 * be NULL. Length should be the total length of the
2381 * potential variable invocation (from $ to end
2384 if (rval == var_Error || rval == varNoError) {
2386 * If performing old-time variable
2387 * substitution, skip over the variable and
2388 * continue with the substitution. Otherwise,
2389 * store the dollar sign and advance str so
2390 * we continue with the string...
2396 * If variable is undefined, complain
2397 * and skip the variable. The
2398 * complaint will stop us from doing
2399 * anything when the file is parsed.
2401 if (!errorReported) {
2402 Parse_Error(PARSE_FATAL,
2403 "Undefined variable \"%.*s\"", subvp.ptr - subvp.input, str);
2405 errorReported = TRUE;
2408 Buf_AddByte(buf, (Byte)str[0]);
2413 * Copy all the characters from the variable
2414 * value straight into the new string.
2416 Buf_Append(buf, rval);
2423 Buf_AddByte(buf, (Byte)str[0]);
2432 * Substitute for all variables except if it is the same as 'var',
2433 * in the given string in the given context. If err is TRUE,
2434 * Parse_Error will be called when an undefined variable is
2438 * The resulting string.
2441 * None. The old string must be freed by the caller
2444 Var_SubstOnly(const char *var, const char *str, Boolean err)
2446 GNode *ctxt = VAR_GLOBAL;
2447 Boolean errorReported;
2448 Buffer *buf; /* Buffer for forming things */
2451 * Set TRUE if an error has already been reported to prevent a
2452 * plethora of messages when recursing. XXXHB this comment sounds
2455 errorReported = FALSE;
2458 while (str[0] != '\0') {
2459 if (str[0] == '$') {
2462 skip = match_var(str, var);
2464 Buf_AddBytes(buf, skip, str);
2467 /* Variable invocation. */
2478 rval = VarParse(&subvp, &rfree);
2481 * When we get down here, rval should either
2482 * point to the value of this variable, or be
2485 if (rval == var_Error || rval == varNoError) {
2487 * If performing old-time variable
2488 * substitution, skip over the
2489 * variable and continue with the
2490 * substitution. Otherwise, store the
2491 * dollar sign and advance str so we
2492 * continue with the string...
2498 * If variable is undefined,
2499 * complain and skip the
2500 * variable. The complaint
2501 * will stop us from doing
2502 * anything when the file is
2505 if (!errorReported) {
2506 Parse_Error(PARSE_FATAL,
2507 "Undefined variable \"%.*s\"", subvp.ptr - subvp.input, str);
2509 errorReported = TRUE;
2512 Buf_AddByte(buf, (Byte)str[0]);
2517 * Copy all the characters from the
2518 * variable value straight into the
2521 Buf_Append(buf, rval);
2529 Buf_AddByte(buf, (Byte)str[0]);
2538 * Initialize the module
2541 * The VAR_CMD and VAR_GLOBAL contexts are created
2544 Var_Init(char **env)
2548 VAR_CMD = Targ_NewGN("Command");
2549 VAR_ENV = Targ_NewGN("Environment");
2550 VAR_GLOBAL = Targ_NewGN("Global");
2553 * Copy user environment variables into ENV context.
2555 for (ptr = env; *ptr != NULL; ++ptr) {
2556 char *tmp = estrdup(*ptr);
2557 const char *name = tmp;
2558 char *sep = strchr(name, '=');
2559 const char *value = sep + 1;
2563 VarAdd(name, value, VAR_ENV);
2570 * Print all variables in global and command line contexts.
2578 printf("#*** Global Variables:\n");
2579 LST_FOREACH(ln, &VAR_GLOBAL->context) {
2581 printf("%-16s = %s\n", v->name, Buf_Data(v->val));
2584 printf("#*** Command-line Variables:\n");
2585 LST_FOREACH(ln, &VAR_CMD->context) {
2587 printf("%-16s = %s\n", v->name, Buf_Data(v->val));
2592 * Print the values of any variables requested by
2596 Var_Print(Lst *vlist, Boolean expandVars)
2601 LST_FOREACH(n, vlist) {
2602 name = Lst_Datum(n);
2610 v = emalloc(strlen(name) + 1 + 3);
2611 sprintf(v, "${%s}", name);
2613 value = Buf_Peel(Var_Subst(v, VAR_GLOBAL, FALSE));
2614 printf("%s\n", value);
2620 const char *value = Var_Value(name, VAR_GLOBAL);
2621 printf("%s\n", value != NULL ? value : "");