2 * Copyright (c) 2002 Juli Mallett.
3 * Copyright (c) 1988, 1989, 1990, 1993
4 * The Regents of the University of California. All rights reserved.
5 * Copyright (c) 1989 by Berkeley Softworks
8 * This code is derived from software contributed to Berkeley by
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 * @(#)var.c 8.3 (Berkeley) 3/19/94
40 * $FreeBSD: src/usr.bin/make/var.c,v 1.83 2005/02/11 10:49:01 harti Exp $
41 * $DragonFly: src/usr.bin/make/var.c,v 1.214 2005/07/02 10:47:28 okumoto Exp $
46 * Variable-handling functions
49 * Var_Set Set the value of a variable in the given
50 * context. The variable is created if it doesn't
51 * yet exist. The value and variable name need not
54 * Var_Append Append more characters to an existing variable
55 * in the given context. The variable needn't
56 * exist already -- it will be created if it doesn't.
57 * A space is placed between the old value and the
60 * Var_Exists See if a variable exists.
62 * Var_Value Return the value of a variable in a context or
63 * NULL if the variable is undefined.
65 * Var_Subst Substitute named variable, or all variables if
66 * NULL in a string using
67 * the given context as the top-most one. If the
68 * third argument is non-zero, Parse_Error is
69 * called if any variables are undefined.
71 * Var_Parse Parse a variable expansion from a string and
72 * return the result and the number of characters
75 * Var_Delete Delete a variable in a context.
77 * Var_Init Initialize this module.
80 * Var_Dump Print out all variables defined in the given
83 * XXX: There's a lot of duplication in these functions.
90 #include <sys/types.h>
109 typedef struct VarParser {
110 const char *const input; /* pointer to input string */
111 const char *ptr; /* current parser pos in input str */
118 char *name; /* the variable's name */
119 struct Buffer *val; /* its value */
120 int flags; /* miscellaneous status flags */
122 #define VAR_IN_USE 1 /* Variable's value currently being used.
123 * Used to avoid recursion */
125 #define VAR_JUNK 4 /* Variable is a junk variable that
126 * should be destroyed when done with
127 * it. Used by Var_Parse for undefined,
128 * modified variables */
130 #define VAR_TO_ENV 8 /* Place variable in environment */
134 struct Buffer *lhs; /* String to match */
135 struct Buffer *rhs; /* Replacement string (w/ &'s removed) */
142 #define VAR_SUB_GLOBAL 0x01 /* Apply substitution globally */
143 #define VAR_SUB_ONE 0x02 /* Apply substitution to one word */
144 #define VAR_SUB_MATCHED 0x04 /* There was a match */
145 #define VAR_MATCH_START 0x08 /* Match at start of word */
146 #define VAR_MATCH_END 0x10 /* Match at end of word */
149 typedef Boolean VarModifyProc(const char *, Boolean, struct Buffer *, void *);
151 static char *VarParse(VarParser *, Boolean *);
154 * This is a harmless return value for Var_Parse that can be used by Var_Subst
155 * to determine if there was an error in parsing -- easier than returning
156 * a flag, as things outside this module don't give a hoot.
158 char var_Error[] = "";
161 * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
162 * set false. Why not just use a constant? Well, gcc likes to condense
163 * identical string instances...
165 static char varNoError[] = "";
168 * Internally, variables are contained in four different contexts.
169 * 1) the environment. They may not be changed. If an environment
170 * variable is appended-to, the result is placed in the global
172 * 2) the global context. Variables set in the Makefile are located in
173 * the global context. It is the penultimate context searched when
175 * 3) the command-line context. All variables set on the command line
176 * are placed in this context. They are UNALTERABLE once placed here.
177 * 4) the local context. Each target has associated with it a context
178 * list. On this list are located the structures describing such
179 * local variables as $(@) and $(*)
180 * The four contexts are searched in the reverse order from which they are
183 static GNode *VAR_ENV; /* variables from the environment */
184 GNode *VAR_GLOBAL; /* variables from the makefile */
185 GNode *VAR_CMD; /* variables defined on the command-line */
187 Boolean oldVars; /* variable substitution style */
188 Boolean checkEnvFirst; /* -e flag */
190 #define OPEN_PAREN '('
191 #define CLOSE_PAREN ')'
192 #define OPEN_BRACE '{'
193 #define CLOSE_BRACE '}'
196 * Create a Var object.
198 * @param name Name of variable.
199 * @param value Value of variable.
200 * @param flags Flags set on variable.
203 VarCreate(const char name[], const char value[], int flags)
207 v = emalloc(sizeof(Var));
208 v->name = estrdup(name);
209 v->val = Buf_Init(0);
213 Buf_Append(v->val, value);
219 * Destroy a Var object.
221 * @param v Object to destroy.
222 * @param f true if internal buffer in Buffer object is to be
226 VarDestroy(Var *v, Boolean f)
229 Buf_Destroy(v->val, f);
235 * Remove the tail of the given word and place the result in the given
239 * TRUE if characters were added to the buffer (a space needs to be
240 * added to the buffer before the next word).
243 * The trimmed word is added to the buffer.
246 VarHead(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
250 slash = strrchr(word, '/');
253 Buf_AddByte(buf, (Byte)' ');
255 Buf_AppendRange(buf, word, slash);
258 * If no directory part, give . (q.v. the POSIX standard)
261 Buf_Append(buf, " .");
263 Buf_AddByte(buf, (Byte)'.');
270 * Remove the head of the given word and place the result in the given
274 * TRUE if characters were added to the buffer (a space needs to be
275 * added to the buffer before the next word).
278 * The trimmed word is added to the buffer.
281 VarTail(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
286 Buf_AddByte(buf, (Byte)' ');
289 slash = strrchr(word, '/');
292 Buf_Append(buf, slash);
294 Buf_Append(buf, word);
300 * Place the suffix of the given word in the given buffer.
303 * TRUE if characters were added to the buffer (a space needs to be
304 * added to the buffer before the next word).
307 * The suffix from the word is placed in the buffer.
310 VarSuffix(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
314 dot = strrchr(word, '.');
317 Buf_AddByte(buf, (Byte)' ');
320 Buf_Append(buf, dot);
327 * Remove the suffix of the given word and place the result in the
331 * TRUE if characters were added to the buffer (a space needs to be
332 * added to the buffer before the next word).
335 * The trimmed word is added to the buffer.
338 VarRoot(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
343 Buf_AddByte(buf, (Byte)' ');
346 dot = strrchr(word, '.');
348 Buf_AppendRange(buf, word, dot);
350 Buf_Append(buf, word);
356 * Place the word in the buffer if it matches the given pattern.
357 * Callback function for VarModify to implement the :M modifier.
358 * A space will be added if requested. A pattern is supplied
359 * which the word must match.
362 * TRUE if a space should be placed in the buffer before the next
366 * The word may be copied to the buffer.
369 VarMatch(const char *word, Boolean addSpace, Buffer *buf, void *pattern)
372 if (Str_Match(word, pattern)) {
374 Buf_AddByte(buf, (Byte)' ');
377 Buf_Append(buf, word);
384 * Place the word in the buffer if it matches the given pattern.
385 * Callback function for VarModify to implement the System V %
386 * modifiers. A space is added if requested.
389 * TRUE if a space should be placed in the buffer before the next
393 * The word may be copied to the buffer.
396 VarSYSVMatch(const char *word, Boolean addSpace, Buffer *buf, void *patp)
400 VarPattern *pat = (VarPattern *)patp;
403 Buf_AddByte(buf, (Byte)' ');
407 if ((ptr = Str_SYSVMatch(word, Buf_Data(pat->lhs), &len)) != NULL)
408 Str_SYSVSubst(buf, Buf_Data(pat->rhs), ptr, len);
410 Buf_Append(buf, word);
417 * Place the word in the buffer if it doesn't match the given pattern.
418 * Callback function for VarModify to implement the :N modifier. A
419 * space is added if requested.
422 * TRUE if a space should be placed in the buffer before the next
426 * The word may be copied to the buffer.
429 VarNoMatch(const char *word, Boolean addSpace, Buffer *buf, void *pattern)
432 if (!Str_Match(word, pattern)) {
434 Buf_AddByte(buf, (Byte)' ');
437 Buf_Append(buf, word);
443 * Perform a string-substitution on the given word, placing the
444 * result in the passed buffer. A space is added if requested.
447 * TRUE if a space is needed before more characters are added.
450 VarSubstitute(const char *word, Boolean addSpace, Buffer *buf, void *patternp)
452 size_t wordLen; /* Length of word */
453 const char *cp; /* General pointer */
454 VarPattern *pattern = patternp;
456 wordLen = strlen(word);
457 if (1) { /* substitute in each word of the variable */
459 * Break substitution down into simple anchored cases
460 * and if none of them fits, perform the general substitution
463 if ((pattern->flags & VAR_MATCH_START) &&
464 (strncmp(word, Buf_Data(pattern->lhs),
465 Buf_Size(pattern->lhs)) == 0)) {
467 * Anchored at start and beginning of word matches
470 if ((pattern->flags & VAR_MATCH_END) &&
471 (wordLen == Buf_Size(pattern->lhs))) {
473 * Also anchored at end and matches to the end
474 * (word is same length as pattern) add space
475 * and rhs only if rhs is non-null.
477 if (Buf_Size(pattern->rhs) != 0) {
479 Buf_AddByte(buf, (Byte)' ');
482 Buf_AppendBuf(buf, pattern->rhs);
485 } else if (pattern->flags & VAR_MATCH_END) {
487 * Doesn't match to end -- copy word wholesale
493 * Matches at start but need to copy in
494 * trailing characters.
496 if ((Buf_Size(pattern->rhs) + wordLen -
497 Buf_Size(pattern->lhs)) != 0) {
499 Buf_AddByte(buf, (Byte)' ');
503 Buf_AppendBuf(buf, pattern->rhs);
504 Buf_AddBytes(buf, wordLen -
505 Buf_Size(pattern->lhs),
506 (word + Buf_Size(pattern->lhs)));
509 } else if (pattern->flags & VAR_MATCH_START) {
511 * Had to match at start of word and didn't -- copy
516 } else if (pattern->flags & VAR_MATCH_END) {
518 * Anchored at end, Find only place match could occur
519 * (leftLen characters from the end of the word) and
520 * see if it does. Note that because the $ will be
521 * left at the end of the lhs, we have to use strncmp.
523 cp = word + (wordLen - Buf_Size(pattern->lhs));
524 if ((cp >= word) && (strncmp(cp, Buf_Data(pattern->lhs),
525 Buf_Size(pattern->lhs)) == 0)) {
527 * Match found. If we will place characters in
528 * the buffer, add a space before hand as
529 * indicated by addSpace, then stuff in the
530 * initial, unmatched part of the word followed
531 * by the right-hand-side.
533 if ((cp - word) + Buf_Size(pattern->rhs) != 0) {
535 Buf_AddByte(buf, (Byte)' ');
539 Buf_AppendRange(buf, word, cp);
540 Buf_AppendBuf(buf, pattern->rhs);
544 * Had to match at end and didn't. Copy entire
551 * Pattern is unanchored: search for the pattern in the
552 * word using strstr(3), copying unmatched portions and
553 * the right-hand-side for each match found, handling
554 * non-global substitutions correctly, etc. When the
555 * loop is done, any remaining part of the word (word
556 * and wordLen are adjusted accordingly through the
557 * loop) is copied straight into the buffer.
558 * addSpace is set FALSE as soon as a space is added
565 origSize = Buf_Size(buf);
567 cp = strstr(word, Buf_Data(pattern->lhs));
569 if (addSpace && (((cp - word) +
570 Buf_Size(pattern->rhs)) != 0)) {
571 Buf_AddByte(buf, (Byte)' ');
574 Buf_AppendRange(buf, word, cp);
575 Buf_AppendBuf(buf, pattern->rhs);
576 wordLen -= (cp - word) +
577 Buf_Size(pattern->lhs);
578 word = cp + Buf_Size(pattern->lhs);
579 if (wordLen == 0 || (pattern->flags &
580 VAR_SUB_GLOBAL) == 0) {
589 Buf_AddByte(buf, (Byte)' ');
591 Buf_AddBytes(buf, wordLen, (const Byte *)word);
595 * If added characters to the buffer, need to add a
596 * space before we add any more. If we didn't add any,
597 * just return the previous value of addSpace.
599 return ((Buf_Size(buf) != origSize) || addSpace);
602 * Common code for anchored substitutions:
603 * addSpace was set TRUE if characters were added to the buffer.
609 Buf_AddByte(buf, (Byte)' ');
611 Buf_AddBytes(buf, wordLen, (const Byte *)word);
616 * Print the error caused by a regcomp or regexec call.
619 * An error gets printed.
622 VarREError(int err, regex_t *pat, const char *str)
627 errlen = regerror(err, pat, 0, 0);
628 errbuf = emalloc(errlen);
629 regerror(err, pat, errbuf, errlen);
630 Error("%s: %s", str, errbuf);
636 * Perform a regex substitution on the given word, placing the
637 * result in the passed buffer. A space is added if requested.
640 * TRUE if a space is needed before more characters are added.
643 VarRESubstitute(const char *word, Boolean addSpace, Buffer *buf, void *patternp)
652 #define MAYBE_ADD_SPACE() \
653 if (addSpace && !added) \
654 Buf_AddByte(buf, (Byte)' '); \
661 if ((pat->flags & (VAR_SUB_ONE | VAR_SUB_MATCHED)) ==
662 (VAR_SUB_ONE | VAR_SUB_MATCHED)) {
666 xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
671 pat->flags |= VAR_SUB_MATCHED;
672 if (pat->matches[0].rm_so > 0) {
674 Buf_AddBytes(buf, pat->matches[0].rm_so,
678 for (rp = Buf_Data(pat->rhs); *rp; rp++) {
679 if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
681 Buf_AddByte(buf, (Byte)rp[1]);
684 } else if ((*rp == '&') ||
685 ((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
704 Error("No subexpression %s",
709 } else if ((pat->matches[n].rm_so == -1) &&
710 (pat->matches[n].rm_eo == -1)) {
711 Error("No match for subexpression %s",
717 subbuf = wp + pat->matches[n].rm_so;
718 sublen = pat->matches[n].rm_eo -
719 pat->matches[n].rm_so;
724 Buf_AddBytes(buf, sublen,
725 (const Byte *)subbuf);
729 Buf_AddByte(buf, (Byte)*rp);
732 wp += pat->matches[0].rm_eo;
733 if (pat->flags & VAR_SUB_GLOBAL) {
735 if (pat->matches[0].rm_so == 0 &&
736 pat->matches[0].rm_eo == 0) {
738 Buf_AddByte(buf, (Byte)*wp);
751 VarREError(xrv, &pat->re, "Unexpected regex error");
761 return (addSpace || added);
765 * Find a variable in a variable list.
768 VarLookup(Lst *vlist, const char *name)
772 LST_FOREACH(ln, vlist)
773 if (strcmp(((const Var *)Lst_Datum(ln))->name, name) == 0)
774 return (Lst_Datum(ln));
779 * Expand a variable name's embedded variables in the given context.
782 * The contents of name, possibly expanded.
785 VarPossiblyExpand(const char *name, GNode *ctxt)
789 if (strchr(name, '$') != NULL) {
790 buf = Var_Subst(name, ctxt, 0);
791 return (Buf_Peel(buf));
793 return estrdup(name);
798 * If the variable name begins with a '.', it could very well be
799 * one of the local ones. We check the name against all the local
800 * variables and substitute the short version in for 'name' if it
801 * matches one of them.
804 VarLocal(const char name[])
806 if (name[0] == '.') {
809 if (!strcmp(name, ".ALLSRC"))
811 if (!strcmp(name, ".ARCHIVE"))
815 if (!strcmp(name, ".IMPSRC"))
819 if (!strcmp(name, ".MEMBER"))
823 if (!strcmp(name, ".OODATE"))
827 if (!strcmp(name, ".PREFIX"))
831 if (!strcmp(name, ".TARGET"))
842 * Find the given variable in the given context and the environment.
845 * A pointer to the structure describing the desired variable or
846 * NULL if the variable does not exist.
849 VarFindEnv(const char name[], GNode *ctxt)
853 name = VarLocal(name);
855 if ((var = VarLookup(&ctxt->context, name)) != NULL)
858 if ((var = VarLookup(&VAR_ENV->context, name)) != NULL)
865 * Look for the variable in the given context.
868 VarFindOnly(const char name[], GNode *ctxt)
871 return (VarLookup(&ctxt->context, VarLocal(name)));
875 * Look for the variable in all contexts.
878 VarFindAny(const char name[], GNode *ctxt)
880 Boolean localCheckEnvFirst;
884 name = VarLocal(name);
887 * Note whether this is one of the specific variables we were told
888 * through the -E flag to use environment-variable-override for.
890 localCheckEnvFirst = FALSE;
891 LST_FOREACH(ln, &envFirstVars) {
892 if (strcmp(Lst_Datum(ln), name) == 0) {
893 localCheckEnvFirst = TRUE;
899 * First look for the variable in the given context. If it's not there,
900 * look for it in VAR_CMD, VAR_GLOBAL and the environment,
901 * in that order, depending on the FIND_* flags in 'flags'
903 if ((var = VarLookup(&ctxt->context, name)) != NULL)
906 /* not there - try command line context */
907 if (ctxt != VAR_CMD) {
908 if ((var = VarLookup(&VAR_CMD->context, name)) != NULL)
912 /* not there - try global context, but only if not -e/-E */
913 if (ctxt != VAR_GLOBAL && (!checkEnvFirst && !localCheckEnvFirst)) {
914 if ((var = VarLookup(&VAR_GLOBAL->context, name)) != NULL)
918 if ((var = VarLookup(&VAR_ENV->context, name)) != NULL)
921 /* deferred check for the environment (in case of -e/-E) */
922 if ((ctxt != VAR_GLOBAL) && (checkEnvFirst || localCheckEnvFirst)) {
923 if ((var = VarLookup(&VAR_GLOBAL->context, name)) != NULL)
931 * Add a new variable of name name and value val to the given context.
934 * The new variable is placed at the front of the given context
935 * The name and val arguments are duplicated so they may
939 VarAdd(const char *name, const char *val, GNode *ctxt)
942 Lst_AtFront(&ctxt->context, VarCreate(name, val, 0));
943 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
947 * Remove a variable from a context.
950 * The Var structure is removed and freed.
953 Var_Delete(const char *name, GNode *ctxt)
957 DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
958 LST_FOREACH(ln, &ctxt->context) {
959 if (strcmp(((const Var *)Lst_Datum(ln))->name, name) == 0) {
960 VarDestroy(Lst_Datum(ln), TRUE);
961 Lst_Remove(&ctxt->context, ln);
968 * Set the variable name to the value val in the given context.
971 * If the variable doesn't yet exist, a new record is created for it.
972 * Else the old value is freed and the new one stuck in its place
975 * The variable is searched for only in its context before being
976 * created in that context. I.e. if the context is VAR_GLOBAL,
977 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
978 * VAR_CMD->context is searched. This is done to avoid the literally
979 * thousands of unnecessary strcmp's that used to be done to
980 * set, say, $(@) or $(<).
983 Var_Set(const char *name, const char *val, GNode *ctxt)
989 * We only look for a variable in the given context since anything
990 * set here will override anything in a lower context, so there's not
991 * much point in searching them all just to save a bit of memory...
993 n = VarPossiblyExpand(name, ctxt);
994 v = VarFindOnly(n, ctxt);
996 VarAdd(n, val, ctxt);
997 if (ctxt == VAR_CMD) {
999 * Any variables given on the command line
1000 * are automatically exported to the
1001 * environment (as per POSIX standard)
1007 Buf_Append(v->val, val);
1009 if (ctxt == VAR_CMD || (v->flags & VAR_TO_ENV)) {
1011 * Any variables given on the command line
1012 * are automatically exported to the
1013 * environment (as per POSIX standard)
1020 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, val));
1025 * Set the a global name variable to the value.
1028 Var_SetGlobal(const char name[], const char value[])
1031 Var_Set(name, value, VAR_GLOBAL);
1036 * Set the VAR_TO_ENV flag on a variable
1039 Var_SetEnv(const char *name, GNode *ctxt)
1043 v = VarFindOnly(name, VAR_CMD);
1046 * Do not allow .EXPORT: to be set on variables
1047 * from the command line or MAKEFLAGS.
1050 "Warning: Did not set .EXPORTVAR: on %s because it "
1051 "is from the command line or MAKEFLAGS", name);
1055 v = VarFindAny(name, ctxt);
1057 Lst_AtFront(&VAR_ENV->context,
1058 VarCreate(name, NULL, VAR_TO_ENV));
1059 setenv(name, "", 1);
1060 Error("Warning: .EXPORTVAR: set on undefined variable %s", name);
1062 if ((v->flags & VAR_TO_ENV) == 0) {
1063 v->flags |= VAR_TO_ENV;
1064 setenv(v->name, Buf_Data(v->val), 1);
1070 * The variable of the given name has the given value appended to it in
1071 * the given context.
1074 * If the variable doesn't exist, it is created. Else the strings
1075 * are concatenated (with a space in between).
1078 * Only if the variable is being sought in the global context is the
1079 * environment searched.
1080 * XXX: Knows its calling circumstances in that if called with ctxt
1081 * an actual target, it will only search that context since only
1082 * a local variable could be being appended to. This is actually
1083 * a big win and must be tolerated.
1086 Var_Append(const char *name, const char *val, GNode *ctxt)
1091 n = VarPossiblyExpand(name, ctxt);
1092 if (ctxt == VAR_GLOBAL) {
1093 v = VarFindEnv(n, ctxt);
1095 v = VarFindOnly(n, ctxt);
1098 VarAdd(n, val, ctxt);
1100 Buf_AddByte(v->val, (Byte)' ');
1101 Buf_Append(v->val, val);
1102 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, Buf_Data(v->val)));
1108 * See if the given variable exists.
1111 * TRUE if it does, FALSE if it doesn't
1114 Var_Exists(const char *name, GNode *ctxt)
1119 n = VarPossiblyExpand(name, ctxt);
1120 v = VarFindAny(n, ctxt);
1131 * Return the value of the named variable in the given context
1134 * The value if the variable exists, NULL if it doesn't.
1137 Var_Value(const char name[], GNode *ctxt)
1142 n = VarPossiblyExpand(name, ctxt);
1143 v = VarFindAny(n, ctxt);
1148 return (Buf_Data(v->val));
1153 * Modify each of the words of the passed string using the given
1154 * function. Used to implement all modifiers.
1157 * A string of all the words modified appropriately.
1160 VarModify(const char *str, VarModifyProc *modProc, void *datum)
1163 Buffer *buf; /* Buffer for the new string */
1165 Boolean addSpace; /*
1166 * TRUE if need to add a space to
1167 * the buffer before adding the
1171 brk_string(&aa, str, FALSE);
1175 for (i = 1; i < aa.argc; i++)
1176 addSpace = (*modProc)(aa.argv[i], addSpace, buf, datum);
1179 return (Buf_Peel(buf));
1183 * Sort the words in the string.
1186 * str String whose words should be sorted
1187 * cmp A comparison function to control the ordering
1190 * A string containing the words sorted
1193 VarSortWords(const char *str, int (*cmp)(const void *, const void *))
1199 brk_string(&aa, str, FALSE);
1200 qsort(aa.argv + 1, aa.argc - 1, sizeof(char *), cmp);
1203 for (i = 1; i < aa.argc; i++) {
1204 Buf_Append(buf, aa.argv[i]);
1205 Buf_AddByte(buf, (Byte)((i < aa.argc - 1) ? ' ' : '\0'));
1209 return (Buf_Peel(buf));
1213 SortIncreasing(const void *l, const void *r)
1216 return (strcmp(*(const char* const*)l, *(const char* const*)r));
1220 * Pass through the tstr looking for 1) escaped delimiters,
1221 * '$'s and backslashes (place the escaped character in
1222 * uninterpreted) and 2) unescaped $'s that aren't before
1223 * the delimiter (expand the variable substitution).
1224 * Return the expanded string or NULL if the delimiter was missing
1225 * If pattern is specified, handle escaped ampersands, and replace
1226 * unescaped ampersands with the lhs of the pattern.
1229 * A string of all the words modified appropriately.
1230 * If length is specified, return the string length of the buffer
1231 * If flags is specified and the last character of the pattern is a
1232 * $ set the VAR_MATCH_END bit of flags.
1235 VarGetPattern(VarParser *vp, int delim, int *flags, VarPattern *patt)
1242 * Skim through until the matching delimiter is found; pick up
1243 * variable substitutions on the way. Also allow backslashes to quote
1244 * the delimiter, $, and \, but don't touch other backslashes.
1246 while (*vp->ptr != '\0') {
1247 if (*vp->ptr == delim) {
1250 } else if ((vp->ptr[0] == '\\') &&
1251 ((vp->ptr[1] == delim) ||
1252 (vp->ptr[1] == '\\') ||
1253 (vp->ptr[1] == '$') ||
1254 (vp->ptr[1] == '&' && patt != NULL))) {
1255 vp->ptr++; /* consume backslash */
1256 Buf_AddByte(buf, (Byte)vp->ptr[0]);
1259 } else if (vp->ptr[0] == '$') {
1260 if (vp->ptr[1] == delim) {
1261 if (flags == NULL) {
1262 Buf_AddByte(buf, (Byte)vp->ptr[0]);
1266 * Unescaped $ at end of patt =>
1267 * anchor patt at end.
1269 *flags |= VAR_MATCH_END;
1284 * If unescaped dollar sign not
1285 * before the delimiter, assume it's
1286 * a variable substitution and
1289 rval = VarParse(&subvp, &rfree);
1290 Buf_Append(buf, rval);
1293 vp->ptr = subvp.ptr;
1295 } else if (vp->ptr[0] == '&' && patt != NULL) {
1296 Buf_AppendBuf(buf, patt->lhs);
1299 Buf_AddByte(buf, (Byte)vp->ptr[0]);
1304 Buf_Destroy(buf, TRUE);
1309 * Make sure this variable is fully expanded.
1312 VarExpand(Var *v, VarParser *vp)
1317 if (v->flags & VAR_IN_USE) {
1318 Fatal("Variable %s is recursive.", v->name);
1322 v->flags |= VAR_IN_USE;
1325 * Before doing any modification, we have to make sure the
1326 * value has been fully expanded. If it looks like recursion
1327 * might be necessary (there's a dollar sign somewhere in the
1328 * variable's value) we just call Var_Subst to do any other
1329 * substitutions that are necessary. Note that the value
1330 * returned by Var_Subst will have been
1331 * dynamically-allocated, so it will need freeing when we
1334 value = Buf_Data(v->val);
1335 if (strchr(value, '$') == NULL) {
1336 result = strdup(value);
1340 buf = Var_Subst(value, vp->ctxt, vp->err);
1341 result = Buf_Peel(buf);
1344 v->flags &= ~VAR_IN_USE;
1350 * Select only those words in value that match the modifier.
1353 modifier_M(VarParser *vp, const char value[], char endc)
1360 modifier = vp->ptr[0];
1361 vp->ptr++; /* consume 'M' or 'N' */
1364 * Compress the \:'s out of the pattern, so allocate enough
1365 * room to hold the uncompressed pattern and compress the
1366 * pattern into that space.
1368 patt = estrdup(vp->ptr);
1370 while (vp->ptr[0] != '\0') {
1371 if (vp->ptr[0] == endc || vp->ptr[0] == ':') {
1374 if (vp->ptr[0] == '\\' &&
1375 (vp->ptr[1] == endc || vp->ptr[1] == ':')) {
1376 vp->ptr++; /* consume backslash */
1384 if (modifier == 'M') {
1385 newValue = VarModify(value, VarMatch, patt);
1387 newValue = VarModify(value, VarNoMatch, patt);
1395 * Substitute the replacement string for the pattern. The substitution
1396 * is applied to each word in value.
1399 modifier_S(VarParser *vp, const char value[], Var *v)
1407 vp->ptr++; /* consume 'S' */
1409 delim = *vp->ptr; /* used to find end of pattern */
1410 vp->ptr++; /* consume 1st delim */
1413 * If pattern begins with '^', it is anchored to the start of the
1414 * word -- skip over it and flag pattern.
1416 if (*vp->ptr == '^') {
1417 patt.flags |= VAR_MATCH_START;
1421 patt.lhs = VarGetPattern(vp, delim, &patt.flags, NULL);
1422 if (patt.lhs == NULL) {
1424 * LHS didn't end with the delim, complain and exit.
1426 Fatal("Unclosed substitution for %s (%c missing)",
1430 vp->ptr++; /* consume 2nd delim */
1432 patt.rhs = VarGetPattern(vp, delim, NULL, &patt);
1433 if (patt.rhs == NULL) {
1435 * RHS didn't end with the delim, complain and exit.
1437 Fatal("Unclosed substitution for %s (%c missing)",
1441 vp->ptr++; /* consume last delim */
1444 * Check for global substitution. If 'g' after the final delimiter,
1445 * substitution is global and is marked that way.
1447 if (vp->ptr[0] == 'g') {
1448 patt.flags |= VAR_SUB_GLOBAL;
1453 * Global substitution of the empty string causes an infinite number
1454 * of matches, unless anchored by '^' (start of string) or '$' (end
1455 * of string). Catch the infinite substitution here. Note that flags
1456 * can only contain the 3 bits we're interested in so we don't have
1457 * to mask unrelated bits. We can test for equality.
1459 if (Buf_Size(patt.lhs) == 0 && patt.flags == VAR_SUB_GLOBAL)
1460 Fatal("Global substitution of the empty string");
1462 newValue = VarModify(value, VarSubstitute, &patt);
1465 * Free the two strings.
1474 modifier_C(VarParser *vp, char value[], Var *v)
1483 vp->ptr++; /* consume 'C' */
1485 delim = *vp->ptr; /* delimiter between sections */
1487 vp->ptr++; /* consume 1st delim */
1489 patt.lhs = VarGetPattern(vp, delim, NULL, NULL);
1490 if (patt.lhs == NULL) {
1491 Fatal("Unclosed substitution for %s (%c missing)",
1495 vp->ptr++; /* consume 2st delim */
1497 patt.rhs = VarGetPattern(vp, delim, NULL, NULL);
1498 if (patt.rhs == NULL) {
1499 Fatal("Unclosed substitution for %s (%c missing)",
1503 vp->ptr++; /* consume last delim */
1507 patt.flags |= VAR_SUB_GLOBAL;
1508 vp->ptr++; /* consume 'g' */
1511 patt.flags |= VAR_SUB_ONE;
1512 vp->ptr++; /* consume '1' */
1518 error = regcomp(&patt.re, Buf_Data(patt.lhs), REG_EXTENDED);
1520 VarREError(error, &patt.re, "RE substitution error");
1526 patt.nsub = patt.re.re_nsub + 1;
1531 patt.matches = emalloc(patt.nsub * sizeof(regmatch_t));
1533 newValue = VarModify(value, VarRESubstitute, &patt);
1544 sysVvarsub(VarParser *vp, char startc, Var *v, const char value[])
1548 * This can either be a bogus modifier or a System-V substitution
1558 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1563 * First we make a pass through the string trying to verify it is a
1564 * SYSV-make-style translation: it must be: <string1>=<string2>)
1569 while (*cp != '\0' && cnt) {
1572 /* continue looking for endc */
1573 } else if (*cp == endc)
1575 else if (*cp == startc)
1581 if (*cp == endc && eqFound) {
1583 * Now we break this sucker into the lhs and rhs.
1585 patt.lhs = VarGetPattern(vp, '=', &patt.flags, NULL);
1586 if (patt.lhs == NULL) {
1587 Fatal("Unclosed substitution for %s (%c missing)",
1590 vp->ptr++; /* consume '=' */
1592 patt.rhs = VarGetPattern(vp, endc, NULL, &patt);
1593 if (patt.rhs == NULL) {
1594 Fatal("Unclosed substitution for %s (%c missing)",
1599 * SYSV modifications happen through the whole string. Note
1600 * the pattern is anchored at the end.
1602 newStr = VarModify(value, VarSYSVMatch, &patt);
1609 Error("Unknown modifier '%c'\n", *vp->ptr);
1611 while (*vp->ptr != '\0') {
1612 if (*vp->ptr == endc && *vp->ptr == ':') {
1624 * Quote shell meta-characters in the string
1630 Var_Quote(const char *str)
1633 /* This should cover most shells :-( */
1634 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
1636 buf = Buf_Init(MAKE_BSIZE);
1637 for (; *str; str++) {
1638 if (strchr(meta, *str) != NULL)
1639 Buf_AddByte(buf, (Byte)'\\');
1640 Buf_AddByte(buf, (Byte)*str);
1643 return (Buf_Peel(buf));
1648 * Now we need to apply any modifiers the user wants applied.
1651 * words which match the given <pattern>.
1652 * <pattern> is of the standard file
1654 * :S<d><pat1><d><pat2><d>[g]
1655 * Substitute <pat2> for <pat1> in the value
1656 * :C<d><pat1><d><pat2><d>[g]
1657 * Substitute <pat2> for regex <pat1> in the value
1658 * :H Substitute the head of each word
1659 * :T Substitute the tail of each word
1660 * :E Substitute the extension (minus '.') of
1662 * :R Substitute the root of each word
1663 * (pathname minus the suffix).
1665 * Like :S, but the rhs goes to the end of
1667 * :U Converts variable to upper-case.
1668 * :L Converts variable to lower-case.
1670 * XXXHB update this comment or remove it and point to the man page.
1673 ParseModifier(VarParser *vp, char startc, Var *v, Boolean *freeResult)
1678 value = VarExpand(v, vp);
1681 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1683 vp->ptr++; /* consume first colon */
1685 while (*vp->ptr != '\0') {
1686 char *newStr; /* New value to return */
1688 if (*vp->ptr == endc) {
1692 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *vp->ptr, value));
1696 newStr = modifier_M(vp, value, endc);
1699 newStr = modifier_S(vp, value, v);
1702 newStr = modifier_C(vp, value, v);
1705 if (vp->ptr[1] != endc && vp->ptr[1] != ':') {
1707 if ((vp->ptr[0] == 's') &&
1708 (vp->ptr[1] == 'h') &&
1709 (vp->ptr[2] == endc || vp->ptr[2] == ':')) {
1714 Cmd_Exec(value, &error));
1716 newStr = estrdup("");
1720 Error(error, value);
1725 newStr = sysVvarsub(vp, startc, v, value);
1730 switch (vp->ptr[0]) {
1735 buf = Buf_Init(MAKE_BSIZE);
1736 for (cp = value; *cp; cp++)
1737 Buf_AddByte(buf, (Byte)tolower(*cp));
1739 newStr = Buf_Peel(buf);
1745 newStr = VarSortWords(value, SortIncreasing);
1749 newStr = Var_Quote(value);
1753 newStr = VarModify(value, VarTail, NULL);
1760 buf = Buf_Init(MAKE_BSIZE);
1761 for (cp = value; *cp; cp++)
1762 Buf_AddByte(buf, (Byte)toupper(*cp));
1764 newStr = Buf_Peel(buf);
1770 newStr = VarModify(value, VarHead, NULL);
1774 newStr = VarModify(value, VarSuffix, NULL);
1778 newStr = VarModify(value, VarRoot, NULL);
1782 newStr = sysVvarsub(vp, startc, v, value);
1788 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1794 *freeResult = (value == var_Error) ? FALSE : TRUE;
1796 if (vp->ptr[0] == ':') {
1797 vp->ptr++; /* consume colon */
1805 ParseRestModifier(VarParser *vp, char startc, Buffer *buf, Boolean *freeResult)
1812 vname = Buf_GetAll(buf, &vlen);
1814 v = VarFindAny(vname, vp->ctxt);
1816 value = ParseModifier(vp, startc, v, freeResult);
1820 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1823 * Still need to get to the end of the variable
1824 * specification, so kludge up a Var structure for the
1827 v = VarCreate(vname, NULL, VAR_JUNK);
1828 value = ParseModifier(vp, startc, v, freeResult);
1832 VarDestroy(v, TRUE);
1834 consumed = vp->ptr - vp->input + 1;
1836 * If substituting a local variable in a non-local context,
1837 * assume it's for dynamic source stuff. We have to handle
1838 * this specially and return the longhand for the variable
1839 * with the dollar sign escaped so it makes it back to the
1840 * caller. Only four of the local variables are treated
1841 * specially as they are the only four that will be set when
1842 * dynamic sources are expanded.
1845 (vlen == 2 && (vname[1] == 'F' || vname[1] == 'D'))) {
1846 if (strchr("!%*@", vname[0]) != NULL) {
1847 value = emalloc(consumed + 1);
1848 strncpy(value, vp->input, consumed);
1849 value[consumed] = '\0';
1857 isupper((unsigned char)vname[1])) {
1858 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1859 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1860 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1861 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1862 value = emalloc(consumed + 1);
1863 strncpy(value, vp->input, consumed);
1864 value[consumed] = '\0';
1871 *freeResult = FALSE;
1872 return (vp->err ? var_Error : varNoError);
1875 * Check for D and F forms of local variables since we're in
1876 * a local context and the name is the right length.
1879 (vname[1] == 'F' || vname[1] == 'D') &&
1880 (strchr("!%*<>@", vname[0]) != NULL)) {
1886 v = VarFindOnly(name, vp->ctxt);
1888 value = ParseModifier(vp, startc, v, freeResult);
1894 * Still need to get to the end of the variable
1895 * specification, so kludge up a Var structure for the
1898 v = VarCreate(vname, NULL, VAR_JUNK);
1899 value = ParseModifier(vp, startc, v, freeResult);
1903 VarDestroy(v, TRUE);
1905 *freeResult = FALSE;
1906 return (vp->err ? var_Error : varNoError);
1911 ParseRestEnd(VarParser *vp, Buffer *buf, Boolean *freeResult)
1918 vname = Buf_GetAll(buf, &vlen);
1920 v = VarFindAny(vname, vp->ctxt);
1922 value = VarExpand(v, vp);
1927 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1928 size_t consumed = vp->ptr - vp->input + 1;
1931 * If substituting a local variable in a non-local context,
1932 * assume it's for dynamic source stuff. We have to handle
1933 * this specially and return the longhand for the variable
1934 * with the dollar sign escaped so it makes it back to the
1935 * caller. Only four of the local variables are treated
1936 * specially as they are the only four that will be set when
1937 * dynamic sources are expanded.
1940 (vlen == 2 && (vname[1] == 'F' || vname[1] == 'D'))) {
1941 if (strchr("!%*@", vname[0]) != NULL) {
1942 value = emalloc(consumed + 1);
1943 strncpy(value, vp->input, consumed);
1944 value[consumed] = '\0';
1952 isupper((unsigned char)vname[1])) {
1953 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1954 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1955 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1956 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1957 value = emalloc(consumed + 1);
1958 strncpy(value, vp->input, consumed);
1959 value[consumed] = '\0';
1967 * Check for D and F forms of local variables since we're in
1968 * a local context and the name is the right length.
1971 (vname[1] == 'F' || vname[1] == 'D') &&
1972 (strchr("!%*<>@", vname[0]) != NULL)) {
1978 v = VarFindOnly(name, vp->ctxt);
1982 * No need for nested expansion or anything,
1983 * as we're the only one who sets these
1984 * things and we sure don't put nested
1985 * invocations in them...
1987 val = Buf_Data(v->val);
1989 if (vname[1] == 'D') {
1990 val = VarModify(val, VarHead, NULL);
1992 val = VarModify(val, VarTail, NULL);
2001 *freeResult = FALSE;
2002 return (vp->err ? var_Error : varNoError);
2006 * Parse a multi letter variable name, and return it's value.
2009 VarParseLong(VarParser *vp, Boolean *freeResult)
2016 buf = Buf_Init(MAKE_BSIZE);
2018 startc = vp->ptr[0];
2019 vp->ptr++; /* consume opening paren or brace */
2021 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
2024 * Process characters until we reach an end character or a colon,
2025 * replacing embedded variables as we go.
2027 while (*vp->ptr != '\0') {
2028 if (*vp->ptr == endc) {
2029 value = ParseRestEnd(vp, buf, freeResult);
2030 vp->ptr++; /* consume closing paren or brace */
2031 Buf_Destroy(buf, TRUE);
2034 } else if (*vp->ptr == ':') {
2035 value = ParseRestModifier(vp, startc, buf, freeResult);
2036 vp->ptr++; /* consume closing paren or brace */
2037 Buf_Destroy(buf, TRUE);
2040 } else if (*vp->ptr == '$') {
2051 rval = VarParse(&subvp, &rfree);
2052 if (rval == var_Error) {
2053 Fatal("Error expanding embedded variable.");
2055 Buf_Append(buf, rval);
2058 vp->ptr = subvp.ptr;
2060 Buf_AddByte(buf, (Byte)*vp->ptr);
2065 /* If we did not find the end character, return var_Error */
2066 Buf_Destroy(buf, TRUE);
2067 *freeResult = FALSE;
2072 * Parse a single letter variable name, and return it's value.
2075 VarParseShort(VarParser *vp, Boolean *freeResult)
2081 vname[0] = vp->ptr[0];
2084 vp->ptr++; /* consume single letter */
2086 v = VarFindAny(vname, vp->ctxt);
2088 value = VarExpand(v, vp);
2094 * If substituting a local variable in a non-local context, assume
2095 * it's for dynamic source stuff. We have to handle this specially
2096 * and return the longhand for the variable with the dollar sign
2097 * escaped so it makes it back to the caller. Only four of the local
2098 * variables are treated specially as they are the only four that
2099 * will be set when dynamic sources are expanded.
2101 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
2103 /* XXX: It looks like $% and $! are reversed here */
2107 return (estrdup("$(.TARGET)"));
2110 return (estrdup("$(.ARCHIVE)"));
2113 return (estrdup("$(.PREFIX)"));
2116 return (estrdup("$(.MEMBER)"));
2118 *freeResult = FALSE;
2119 return (vp->err ? var_Error : varNoError);
2123 /* Variable name was not found. */
2124 *freeResult = FALSE;
2125 return (vp->err ? var_Error : varNoError);
2129 VarParse(VarParser *vp, Boolean *freeResult)
2132 vp->ptr++; /* consume '$' or last letter of conditional */
2134 if (vp->ptr[0] == '\0') {
2135 /* Error, there is only a dollar sign in the input string. */
2136 *freeResult = FALSE;
2137 return (vp->err ? var_Error : varNoError);
2139 } else if (vp->ptr[0] == OPEN_PAREN || vp->ptr[0] == OPEN_BRACE) {
2140 /* multi letter variable name */
2141 return (VarParseLong(vp, freeResult));
2144 /* single letter variable name */
2145 return (VarParseShort(vp, freeResult));
2150 * Given the start of a variable invocation, extract the variable
2151 * name and find its value, then modify it according to the
2155 * The value of the variable or var_Error if the specification
2156 * is invalid. The number of characters in the specification
2157 * is placed in the variable pointed to by consumed. (for
2158 * invalid specifications, this is just 2 to skip the '$' and
2159 * the following letter, or 1 if '$' was the last character
2160 * in the string). A Boolean in *freeResult telling whether the
2161 * returned string should be freed by the caller.
2164 Var_Parse(const char input[], GNode *ctxt, Boolean err,
2165 size_t *consumed, Boolean *freeResult)
2176 value = VarParse(&vp, freeResult);
2177 *consumed += vp.ptr - vp.input;
2182 * Given the start of a variable invocation, determine the length
2183 * of the specification.
2186 * The number of characters in the specification. For invalid
2187 * specifications, this is just 2 to skip the '$' and the
2188 * following letter, or 1 if '$' was the last character in the
2192 Var_Match(const char input[], GNode *ctxt)
2204 value = VarParse(&vp, &freeResult);
2208 return (vp.ptr - vp.input);
2212 match_var(const char str[], const char var[])
2214 const char *start = str;
2217 str++; /* consume '$' */
2219 if (str[0] == OPEN_PAREN || str[0] == OPEN_BRACE) {
2220 str++; /* consume opening paren or brace */
2222 while (str[0] != '\0') {
2223 if (str[0] == '$') {
2225 * A variable inside the variable. We cannot
2226 * expand the external variable yet.
2228 return (str - start);
2229 } else if (str[0] == ':' ||
2230 str[0] == CLOSE_PAREN ||
2231 str[0] == CLOSE_BRACE) {
2232 len = str - (start + 2);
2234 if (var[len] == '\0' && strncmp(var, start + 2, len) == 0) {
2235 return (0); /* match */
2238 * Not the variable we want to
2241 return (str - start);
2247 return (str - start);
2249 /* Single letter variable name */
2250 if (var[1] == '\0' && var[0] == str[0]) {
2251 return (0); /* match */
2253 str++; /* consume variable name */
2254 return (str - start);
2260 * Substitute for all variables in the given string in the given
2261 * context If err is TRUE, Parse_Error will be called when an
2262 * undefined variable is encountered.
2265 * The resulting string.
2268 * None. The old string must be freed by the caller
2271 Var_Subst(const char *str, GNode *ctxt, Boolean err)
2273 Boolean errorReported;
2274 Buffer *buf; /* Buffer for forming things */
2277 * Set TRUE if an error has already been reported to prevent a
2278 * plethora of messages when recursing. XXXHB this comment sounds
2281 errorReported = FALSE;
2284 while (str[0] != '\0') {
2285 if ((str[0] == '$') && (str[1] == '$')) {
2287 * A dollar sign may be escaped with another dollar
2288 * sign. In such a case, we skip over the escape
2289 * character and store the dollar sign into the
2293 Buf_AddByte(buf, (Byte)str[0]);
2296 } else if (str[0] == '$') {
2297 /* Variable invocation. */
2308 rval = VarParse(&subvp, &rfree);
2311 * When we come down here, val should either point to
2312 * the value of this variable, suitably modified, or
2313 * be NULL. Length should be the total length of the
2314 * potential variable invocation (from $ to end
2317 if (rval == var_Error || rval == varNoError) {
2319 * If performing old-time variable
2320 * substitution, skip over the variable and
2321 * continue with the substitution. Otherwise,
2322 * store the dollar sign and advance str so
2323 * we continue with the string...
2329 * If variable is undefined, complain
2330 * and skip the variable. The
2331 * complaint will stop us from doing
2332 * anything when the file is parsed.
2334 if (!errorReported) {
2335 Parse_Error(PARSE_FATAL,
2336 "Undefined variable \"%.*s\"", subvp.ptr - subvp.input, str);
2338 errorReported = TRUE;
2341 Buf_AddByte(buf, (Byte)str[0]);
2346 * Copy all the characters from the variable
2347 * value straight into the new string.
2349 Buf_Append(buf, rval);
2356 Buf_AddByte(buf, (Byte)str[0]);
2365 * Substitute for all variables except if it is the same as 'var',
2366 * in the given string in the given context. If err is TRUE,
2367 * Parse_Error will be called when an undefined variable is
2371 * The resulting string.
2374 * None. The old string must be freed by the caller
2377 Var_SubstOnly(const char *var, const char *str, Boolean err)
2379 GNode *ctxt = VAR_GLOBAL;
2380 Boolean errorReported;
2381 Buffer *buf; /* Buffer for forming things */
2384 * Set TRUE if an error has already been reported to prevent a
2385 * plethora of messages when recursing. XXXHB this comment sounds
2388 errorReported = FALSE;
2391 while (str[0] != '\0') {
2392 if (str[0] == '$') {
2395 skip = match_var(str, var);
2397 Buf_AddBytes(buf, skip, str);
2400 /* Variable invocation. */
2411 rval = VarParse(&subvp, &rfree);
2414 * When we get down here, rval should either
2415 * point to the value of this variable, or be
2418 if (rval == var_Error || rval == varNoError) {
2420 * If performing old-time variable
2421 * substitution, skip over the
2422 * variable and continue with the
2423 * substitution. Otherwise, store the
2424 * dollar sign and advance str so we
2425 * continue with the string...
2431 * If variable is undefined,
2432 * complain and skip the
2433 * variable. The complaint
2434 * will stop us from doing
2435 * anything when the file is
2438 if (!errorReported) {
2439 Parse_Error(PARSE_FATAL,
2440 "Undefined variable \"%.*s\"", subvp.ptr - subvp.input, str);
2442 errorReported = TRUE;
2445 Buf_AddByte(buf, (Byte)str[0]);
2450 * Copy all the characters from the
2451 * variable value straight into the
2454 Buf_Append(buf, rval);
2462 Buf_AddByte(buf, (Byte)str[0]);
2471 * Initialize the module
2474 * The VAR_CMD and VAR_GLOBAL contexts are created
2477 Var_Init(char **env)
2481 VAR_CMD = Targ_NewGN("Command");
2482 VAR_ENV = Targ_NewGN("Environment");
2483 VAR_GLOBAL = Targ_NewGN("Global");
2486 * Copy user environment variables into ENV context.
2488 for (ptr = env; *ptr != NULL; ++ptr) {
2489 char *tmp = estrdup(*ptr);
2490 const char *name = tmp;
2491 char *sep = strchr(name, '=');
2492 const char *value = sep + 1;
2496 VarAdd(name, value, VAR_ENV);
2503 * Print all variables in global and command line contexts.
2511 printf("#*** Global Variables:\n");
2512 LST_FOREACH(ln, &VAR_GLOBAL->context) {
2514 printf("%-16s = %s\n", v->name, Buf_Data(v->val));
2517 printf("#*** Command-line Variables:\n");
2518 LST_FOREACH(ln, &VAR_CMD->context) {
2520 printf("%-16s = %s\n", v->name, Buf_Data(v->val));
2525 * Print the values of any variables requested by
2529 Var_Print(Lst *vlist, Boolean expandVars)
2533 LST_FOREACH(n, vlist) {
2534 const char *name = Lst_Datum(n);
2540 v = emalloc(strlen(name) + 1 + 3);
2541 sprintf(v, "${%s}", name);
2543 value = Buf_Peel(Var_Subst(v, VAR_GLOBAL, FALSE));
2544 printf("%s\n", value);
2549 const char *value = Var_Value(name, VAR_GLOBAL);
2550 printf("%s\n", value != NULL ? value : "");