2 * Copyright (c) 1988, 1989, 1990, 1993
3 * The Regents of the University of California. All rights reserved.
4 * Copyright (c) 1989 by Berkeley Softworks
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the University of
21 * California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * @(#)var.c 8.3 (Berkeley) 3/19/94
39 * $FreeBSD: src/usr.bin/make/var.c,v 1.16.2.3 2002/02/27 14:18:57 cjc Exp $
40 * $DragonFly: src/usr.bin/make/var.c,v 1.2 2003/06/17 04:29:29 dillon Exp $
45 * Variable-handling functions
48 * Var_Set Set the value of a variable in the given
49 * context. The variable is created if it doesn't
50 * yet exist. The value and variable name need not
53 * Var_Append Append more characters to an existing variable
54 * in the given context. The variable needn't
55 * exist already -- it will be created if it doesn't.
56 * A space is placed between the old value and the
59 * Var_Exists See if a variable exists.
61 * Var_Value Return the value of a variable in a context or
62 * NULL if the variable is undefined.
64 * Var_Subst Substitute named variable, or all variables if
65 * NULL in a string using
66 * the given context as the top-most one. If the
67 * third argument is non-zero, Parse_Error is
68 * called if any variables are undefined.
70 * Var_Parse Parse a variable expansion from a string and
71 * return the result and the number of characters
74 * Var_Delete Delete a variable in a context.
76 * Var_Init Initialize this module.
79 * Var_Dump Print out all variables defined in the given
82 * XXX: There's a lot of duplication in these functions.
86 #include <sys/types.h>
93 * This is a harmless return value for Var_Parse that can be used by Var_Subst
94 * to determine if there was an error in parsing -- easier than returning
95 * a flag, as things outside this module don't give a hoot.
97 char var_Error[] = "";
100 * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
101 * set false. Why not just use a constant? Well, gcc likes to condense
102 * identical string instances...
104 static char varNoError[] = "";
107 * Internally, variables are contained in four different contexts.
108 * 1) the environment. They may not be changed. If an environment
109 * variable is appended-to, the result is placed in the global
111 * 2) the global context. Variables set in the Makefile are located in
112 * the global context. It is the penultimate context searched when
114 * 3) the command-line context. All variables set on the command line
115 * are placed in this context. They are UNALTERABLE once placed here.
116 * 4) the local context. Each target has associated with it a context
117 * list. On this list are located the structures describing such
118 * local variables as $(@) and $(*)
119 * The four contexts are searched in the reverse order from which they are
122 GNode *VAR_GLOBAL; /* variables from the makefile */
123 GNode *VAR_CMD; /* variables defined on the command-line */
125 static Lst allVars; /* List of all variables */
127 #define FIND_CMD 0x1 /* look in VAR_CMD when searching */
128 #define FIND_GLOBAL 0x2 /* look in VAR_GLOBAL as well */
129 #define FIND_ENV 0x4 /* look in the environment also */
132 char *name; /* the variable's name */
133 Buffer val; /* its value */
134 int flags; /* miscellaneous status flags */
135 #define VAR_IN_USE 1 /* Variable's value currently being used.
136 * Used to avoid recursion */
137 #define VAR_FROM_ENV 2 /* Variable comes from the environment */
138 #define VAR_JUNK 4 /* Variable is a junk variable that
139 * should be destroyed when done with
140 * it. Used by Var_Parse for undefined,
141 * modified variables */
144 /* Var*Pattern flags */
145 #define VAR_SUB_GLOBAL 0x01 /* Apply substitution globally */
146 #define VAR_SUB_ONE 0x02 /* Apply substitution to one word */
147 #define VAR_SUB_MATCHED 0x04 /* There was a match */
148 #define VAR_MATCH_START 0x08 /* Match at start of word */
149 #define VAR_MATCH_END 0x10 /* Match at end of word */
150 #define VAR_NOSUBST 0x20 /* don't expand vars in VarGetPattern */
153 char *lhs; /* String to match */
154 int leftLen; /* Length of string */
155 char *rhs; /* Replacement string (w/ &'s removed) */
156 int rightLen; /* Length of replacement */
168 static int VarCmp __P((ClientData, ClientData));
169 static Var *VarFind __P((char *, GNode *, int));
170 static void VarAdd __P((char *, char *, GNode *));
171 static void VarDelete __P((ClientData));
172 static Boolean VarHead __P((char *, Boolean, Buffer, ClientData));
173 static Boolean VarTail __P((char *, Boolean, Buffer, ClientData));
174 static Boolean VarSuffix __P((char *, Boolean, Buffer, ClientData));
175 static Boolean VarRoot __P((char *, Boolean, Buffer, ClientData));
176 static Boolean VarMatch __P((char *, Boolean, Buffer, ClientData));
178 static Boolean VarSYSVMatch __P((char *, Boolean, Buffer, ClientData));
180 static Boolean VarNoMatch __P((char *, Boolean, Buffer, ClientData));
181 static void VarREError __P((int, regex_t *, const char *));
182 static Boolean VarRESubstitute __P((char *, Boolean, Buffer, ClientData));
183 static Boolean VarSubstitute __P((char *, Boolean, Buffer, ClientData));
184 static char *VarGetPattern __P((GNode *, int, char **, int, int *, int *,
186 static char *VarQuote __P((char *));
187 static char *VarModify __P((char *, Boolean (*)(char *, Boolean, Buffer,
190 static int VarPrintVar __P((ClientData, ClientData));
193 *-----------------------------------------------------------------------
195 * See if the given variable matches the named one. Called from
196 * Lst_Find when searching for a variable of a given name.
199 * 0 if they match. non-zero otherwise.
203 *-----------------------------------------------------------------------
207 ClientData v; /* VAR structure to compare */
208 ClientData name; /* name to look for */
210 return (strcmp ((char *) name, ((Var *) v)->name));
214 *-----------------------------------------------------------------------
216 * Find the given variable in the given context and any other contexts
220 * A pointer to the structure describing the desired variable or
221 * NIL if the variable does not exist.
225 *-----------------------------------------------------------------------
228 VarFind (name, ctxt, flags)
229 char *name; /* name to find */
230 GNode *ctxt; /* context in which to find it */
231 int flags; /* FIND_GLOBAL set means to look in the
232 * VAR_GLOBAL context as well.
233 * FIND_CMD set means to look in the VAR_CMD
235 * FIND_ENV set means to look in the
238 Boolean localCheckEnvFirst;
243 * If the variable name begins with a '.', it could very well be one of
244 * the local ones. We check the name against all the local variables
245 * and substitute the short version in for 'name' if it matches one of
248 if (*name == '.' && isupper((unsigned char) name[1]))
251 if (!strcmp(name, ".ALLSRC"))
253 if (!strcmp(name, ".ARCHIVE"))
257 if (!strcmp(name, ".IMPSRC"))
261 if (!strcmp(name, ".MEMBER"))
265 if (!strcmp(name, ".OODATE"))
269 if (!strcmp(name, ".PREFIX"))
273 if (!strcmp(name, ".TARGET"))
279 * Note whether this is one of the specific variables we were told through
280 * the -E flag to use environment-variable-override for.
282 if (Lst_Find (envFirstVars, (ClientData)name,
283 (int (*)(ClientData, ClientData)) strcmp) != NILLNODE)
285 localCheckEnvFirst = TRUE;
287 localCheckEnvFirst = FALSE;
291 * First look for the variable in the given context. If it's not there,
292 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
293 * depending on the FIND_* flags in 'flags'
295 var = Lst_Find (ctxt->context, (ClientData)name, VarCmp);
297 if ((var == NILLNODE) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
298 var = Lst_Find (VAR_CMD->context, (ClientData)name, VarCmp);
300 if ((var == NILLNODE) && (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL) &&
301 !checkEnvFirst && !localCheckEnvFirst)
303 var = Lst_Find (VAR_GLOBAL->context, (ClientData)name, VarCmp);
305 if ((var == NILLNODE) && (flags & FIND_ENV)) {
308 if ((env = getenv (name)) != NULL) {
311 v = (Var *) emalloc(sizeof(Var));
312 v->name = estrdup(name);
316 v->val = Buf_Init(len);
317 Buf_AddBytes(v->val, len, (Byte *)env);
319 v->flags = VAR_FROM_ENV;
321 } else if ((checkEnvFirst || localCheckEnvFirst) &&
322 (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL))
324 var = Lst_Find (VAR_GLOBAL->context, (ClientData)name, VarCmp);
325 if (var == NILLNODE) {
326 return ((Var *) NIL);
328 return ((Var *)Lst_Datum(var));
333 } else if (var == NILLNODE) {
334 return ((Var *) NIL);
336 return ((Var *) Lst_Datum (var));
341 *-----------------------------------------------------------------------
343 * Add a new variable of name name and value val to the given context
349 * The new variable is placed at the front of the given context
350 * The name and val arguments are duplicated so they may
352 *-----------------------------------------------------------------------
355 VarAdd (name, val, ctxt)
356 char *name; /* name of variable to add */
357 char *val; /* value to set it to */
358 GNode *ctxt; /* context in which to set it */
363 v = (Var *) emalloc (sizeof (Var));
365 v->name = estrdup (name);
367 len = val ? strlen(val) : 0;
368 v->val = Buf_Init(len+1);
369 Buf_AddBytes(v->val, len, (Byte *)val);
373 (void) Lst_AtFront (ctxt->context, (ClientData)v);
374 (void) Lst_AtEnd (allVars, (ClientData) v);
376 printf("%s:%s = %s\n", ctxt->name, name, val);
382 *-----------------------------------------------------------------------
384 * Delete a variable and all the space associated with it.
391 *-----------------------------------------------------------------------
399 Buf_Destroy(v->val, TRUE);
406 *-----------------------------------------------------------------------
408 * Remove a variable from a context.
414 * The Var structure is removed and freed.
416 *-----------------------------------------------------------------------
419 Var_Delete(name, ctxt)
426 printf("%s:delete %s\n", ctxt->name, name);
428 ln = Lst_Find(ctxt->context, (ClientData)name, VarCmp);
429 if (ln != NILLNODE) {
432 v = (Var *)Lst_Datum(ln);
433 Lst_Remove(ctxt->context, ln);
434 ln = Lst_Member(allVars, v);
435 Lst_Remove(allVars, ln);
436 VarDelete((ClientData) v);
441 *-----------------------------------------------------------------------
443 * Set the variable name to the value val in the given context.
449 * If the variable doesn't yet exist, a new record is created for it.
450 * Else the old value is freed and the new one stuck in its place
453 * The variable is searched for only in its context before being
454 * created in that context. I.e. if the context is VAR_GLOBAL,
455 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
456 * VAR_CMD->context is searched. This is done to avoid the literally
457 * thousands of unnecessary strcmp's that used to be done to
458 * set, say, $(@) or $(<).
459 *-----------------------------------------------------------------------
462 Var_Set (name, val, ctxt)
463 char *name; /* name of variable to set */
464 char *val; /* value to give to the variable */
465 GNode *ctxt; /* context in which to set it */
470 * We only look for a variable in the given context since anything set
471 * here will override anything in a lower context, so there's not much
472 * point in searching them all just to save a bit of memory...
474 v = VarFind (name, ctxt, 0);
475 if (v == (Var *) NIL) {
476 VarAdd (name, val, ctxt);
478 Buf_Discard(v->val, Buf_Size(v->val));
479 Buf_AddBytes(v->val, strlen(val), (Byte *)val);
482 printf("%s:%s = %s\n", ctxt->name, name, val);
486 * Any variables given on the command line are automatically exported
487 * to the environment (as per POSIX standard)
489 if (ctxt == VAR_CMD) {
490 setenv(name, val, 1);
495 *-----------------------------------------------------------------------
497 * The variable of the given name has the given value appended to it in
504 * If the variable doesn't exist, it is created. Else the strings
505 * are concatenated (with a space in between).
508 * Only if the variable is being sought in the global context is the
509 * environment searched.
510 * XXX: Knows its calling circumstances in that if called with ctxt
511 * an actual target, it will only search that context since only
512 * a local variable could be being appended to. This is actually
513 * a big win and must be tolerated.
514 *-----------------------------------------------------------------------
517 Var_Append (name, val, ctxt)
518 char *name; /* Name of variable to modify */
519 char *val; /* String to append to it */
520 GNode *ctxt; /* Context in which this should occur */
524 v = VarFind (name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
526 if (v == (Var *) NIL) {
527 VarAdd (name, val, ctxt);
529 Buf_AddByte(v->val, (Byte)' ');
530 Buf_AddBytes(v->val, strlen(val), (Byte *)val);
533 printf("%s:%s = %s\n", ctxt->name, name,
534 (char *) Buf_GetAll(v->val, (int *)NULL));
537 if (v->flags & VAR_FROM_ENV) {
539 * If the original variable came from the environment, we
540 * have to install it in the global context (we could place
541 * it in the environment, but then we should provide a way to
542 * export other variables...)
544 v->flags &= ~VAR_FROM_ENV;
545 Lst_AtFront(ctxt->context, (ClientData)v);
551 *-----------------------------------------------------------------------
553 * See if the given variable exists.
556 * TRUE if it does, FALSE if it doesn't
561 *-----------------------------------------------------------------------
564 Var_Exists(name, ctxt)
565 char *name; /* Variable to find */
566 GNode *ctxt; /* Context in which to start search */
570 v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
572 if (v == (Var *)NIL) {
574 } else if (v->flags & VAR_FROM_ENV) {
576 Buf_Destroy(v->val, TRUE);
583 *-----------------------------------------------------------------------
585 * Return the value of the named variable in the given context
588 * The value if the variable exists, NULL if it doesn't
592 *-----------------------------------------------------------------------
595 Var_Value (name, ctxt, frp)
596 char *name; /* name to find */
597 GNode *ctxt; /* context in which to search for it */
602 v = VarFind (name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
604 if (v != (Var *) NIL) {
605 char *p = ((char *)Buf_GetAll(v->val, (int *)NULL));
606 if (v->flags & VAR_FROM_ENV) {
607 Buf_Destroy(v->val, FALSE);
613 return ((char *) NULL);
618 *-----------------------------------------------------------------------
620 * Remove the tail of the given word and place the result in the given
624 * TRUE if characters were added to the buffer (a space needs to be
625 * added to the buffer before the next word).
628 * The trimmed word is added to the buffer.
630 *-----------------------------------------------------------------------
633 VarHead (word, addSpace, buf, dummy)
634 char *word; /* Word to trim */
635 Boolean addSpace; /* True if need to add a space to the buffer
636 * before sticking in the head */
637 Buffer buf; /* Buffer in which to store it */
640 register char *slash;
642 slash = strrchr (word, '/');
643 if (slash != (char *)NULL) {
645 Buf_AddByte (buf, (Byte)' ');
648 Buf_AddBytes (buf, strlen (word), (Byte *)word);
653 * If no directory part, give . (q.v. the POSIX standard)
656 Buf_AddBytes(buf, 2, (Byte *)" .");
658 Buf_AddByte(buf, (Byte)'.');
661 return(dummy ? TRUE : TRUE);
665 *-----------------------------------------------------------------------
667 * Remove the head of the given word and place the result in the given
671 * TRUE if characters were added to the buffer (a space needs to be
672 * added to the buffer before the next word).
675 * The trimmed word is added to the buffer.
677 *-----------------------------------------------------------------------
680 VarTail (word, addSpace, buf, dummy)
681 char *word; /* Word to trim */
682 Boolean addSpace; /* TRUE if need to stick a space in the
683 * buffer before adding the tail */
684 Buffer buf; /* Buffer in which to store it */
687 register char *slash;
690 Buf_AddByte (buf, (Byte)' ');
693 slash = strrchr (word, '/');
694 if (slash != (char *)NULL) {
696 Buf_AddBytes (buf, strlen(slash), (Byte *)slash);
699 Buf_AddBytes (buf, strlen(word), (Byte *)word);
701 return (dummy ? TRUE : TRUE);
705 *-----------------------------------------------------------------------
707 * Place the suffix of the given word in the given buffer.
710 * TRUE if characters were added to the buffer (a space needs to be
711 * added to the buffer before the next word).
714 * The suffix from the word is placed in the buffer.
716 *-----------------------------------------------------------------------
719 VarSuffix (word, addSpace, buf, dummy)
720 char *word; /* Word to trim */
721 Boolean addSpace; /* TRUE if need to add a space before placing
722 * the suffix in the buffer */
723 Buffer buf; /* Buffer in which to store it */
728 dot = strrchr (word, '.');
729 if (dot != (char *)NULL) {
731 Buf_AddByte (buf, (Byte)' ');
734 Buf_AddBytes (buf, strlen (dot), (Byte *)dot);
738 return (dummy ? addSpace : addSpace);
742 *-----------------------------------------------------------------------
744 * Remove the suffix of the given word and place the result in the
748 * TRUE if characters were added to the buffer (a space needs to be
749 * added to the buffer before the next word).
752 * The trimmed word is added to the buffer.
754 *-----------------------------------------------------------------------
757 VarRoot (word, addSpace, buf, dummy)
758 char *word; /* Word to trim */
759 Boolean addSpace; /* TRUE if need to add a space to the buffer
760 * before placing the root in it */
761 Buffer buf; /* Buffer in which to store it */
767 Buf_AddByte (buf, (Byte)' ');
770 dot = strrchr (word, '.');
771 if (dot != (char *)NULL) {
773 Buf_AddBytes (buf, strlen (word), (Byte *)word);
776 Buf_AddBytes (buf, strlen(word), (Byte *)word);
778 return (dummy ? TRUE : TRUE);
782 *-----------------------------------------------------------------------
784 * Place the word in the buffer if it matches the given pattern.
785 * Callback function for VarModify to implement the :M modifier.
788 * TRUE if a space should be placed in the buffer before the next
792 * The word may be copied to the buffer.
794 *-----------------------------------------------------------------------
797 VarMatch (word, addSpace, buf, pattern)
798 char *word; /* Word to examine */
799 Boolean addSpace; /* TRUE if need to add a space to the
800 * buffer before adding the word, if it
802 Buffer buf; /* Buffer in which to store it */
803 ClientData pattern; /* Pattern the word must match */
805 if (Str_Match(word, (char *) pattern)) {
807 Buf_AddByte(buf, (Byte)' ');
810 Buf_AddBytes(buf, strlen(word), (Byte *)word);
817 *-----------------------------------------------------------------------
819 * Place the word in the buffer if it matches the given pattern.
820 * Callback function for VarModify to implement the System V %
824 * TRUE if a space should be placed in the buffer before the next
828 * The word may be copied to the buffer.
830 *-----------------------------------------------------------------------
833 VarSYSVMatch (word, addSpace, buf, patp)
834 char *word; /* Word to examine */
835 Boolean addSpace; /* TRUE if need to add a space to the
836 * buffer before adding the word, if it
838 Buffer buf; /* Buffer in which to store it */
839 ClientData patp; /* Pattern the word must match */
843 VarPattern *pat = (VarPattern *) patp;
846 Buf_AddByte(buf, (Byte)' ');
850 if ((ptr = Str_SYSVMatch(word, pat->lhs, &len)) != NULL)
851 Str_SYSVSubst(buf, pat->rhs, ptr, len);
853 Buf_AddBytes(buf, strlen(word), (Byte *) word);
861 *-----------------------------------------------------------------------
863 * Place the word in the buffer if it doesn't match the given pattern.
864 * Callback function for VarModify to implement the :N modifier.
867 * TRUE if a space should be placed in the buffer before the next
871 * The word may be copied to the buffer.
873 *-----------------------------------------------------------------------
876 VarNoMatch (word, addSpace, buf, pattern)
877 char *word; /* Word to examine */
878 Boolean addSpace; /* TRUE if need to add a space to the
879 * buffer before adding the word, if it
881 Buffer buf; /* Buffer in which to store it */
882 ClientData pattern; /* Pattern the word must match */
884 if (!Str_Match(word, (char *) pattern)) {
886 Buf_AddByte(buf, (Byte)' ');
889 Buf_AddBytes(buf, strlen(word), (Byte *)word);
896 *-----------------------------------------------------------------------
898 * Perform a string-substitution on the given word, placing the
899 * result in the passed buffer.
902 * TRUE if a space is needed before more characters are added.
907 *-----------------------------------------------------------------------
910 VarSubstitute (word, addSpace, buf, patternp)
911 char *word; /* Word to modify */
912 Boolean addSpace; /* True if space should be added before
913 * other characters */
914 Buffer buf; /* Buffer for result */
915 ClientData patternp; /* Pattern for substitution */
917 register int wordLen; /* Length of word */
918 register char *cp; /* General pointer */
919 VarPattern *pattern = (VarPattern *) patternp;
921 wordLen = strlen(word);
922 if (1) { /* substitute in each word of the variable */
924 * Break substitution down into simple anchored cases
925 * and if none of them fits, perform the general substitution case.
927 if ((pattern->flags & VAR_MATCH_START) &&
928 (strncmp(word, pattern->lhs, pattern->leftLen) == 0)) {
930 * Anchored at start and beginning of word matches pattern
932 if ((pattern->flags & VAR_MATCH_END) &&
933 (wordLen == pattern->leftLen)) {
935 * Also anchored at end and matches to the end (word
936 * is same length as pattern) add space and rhs only
937 * if rhs is non-null.
939 if (pattern->rightLen != 0) {
941 Buf_AddByte(buf, (Byte)' ');
944 Buf_AddBytes(buf, pattern->rightLen,
945 (Byte *)pattern->rhs);
947 } else if (pattern->flags & VAR_MATCH_END) {
949 * Doesn't match to end -- copy word wholesale
954 * Matches at start but need to copy in trailing characters
956 if ((pattern->rightLen + wordLen - pattern->leftLen) != 0){
958 Buf_AddByte(buf, (Byte)' ');
962 Buf_AddBytes(buf, pattern->rightLen, (Byte *)pattern->rhs);
963 Buf_AddBytes(buf, wordLen - pattern->leftLen,
964 (Byte *)(word + pattern->leftLen));
966 } else if (pattern->flags & VAR_MATCH_START) {
968 * Had to match at start of word and didn't -- copy whole word.
971 } else if (pattern->flags & VAR_MATCH_END) {
973 * Anchored at end, Find only place match could occur (leftLen
974 * characters from the end of the word) and see if it does. Note
975 * that because the $ will be left at the end of the lhs, we have
978 cp = word + (wordLen - pattern->leftLen);
980 (strncmp(cp, pattern->lhs, pattern->leftLen) == 0)) {
982 * Match found. If we will place characters in the buffer,
983 * add a space before hand as indicated by addSpace, then
984 * stuff in the initial, unmatched part of the word followed
985 * by the right-hand-side.
987 if (((cp - word) + pattern->rightLen) != 0) {
989 Buf_AddByte(buf, (Byte)' ');
993 Buf_AddBytes(buf, cp - word, (Byte *)word);
994 Buf_AddBytes(buf, pattern->rightLen, (Byte *)pattern->rhs);
997 * Had to match at end and didn't. Copy entire word.
1003 * Pattern is unanchored: search for the pattern in the word using
1004 * String_FindSubstring, copying unmatched portions and the
1005 * right-hand-side for each match found, handling non-global
1006 * substitutions correctly, etc. When the loop is done, any
1007 * remaining part of the word (word and wordLen are adjusted
1008 * accordingly through the loop) is copied straight into the
1010 * addSpace is set FALSE as soon as a space is added to the
1013 register Boolean done;
1017 origSize = Buf_Size(buf);
1019 cp = Str_FindSubstring(word, pattern->lhs);
1020 if (cp != (char *)NULL) {
1021 if (addSpace && (((cp - word) + pattern->rightLen) != 0)){
1022 Buf_AddByte(buf, (Byte)' ');
1025 Buf_AddBytes(buf, cp-word, (Byte *)word);
1026 Buf_AddBytes(buf, pattern->rightLen, (Byte *)pattern->rhs);
1027 wordLen -= (cp - word) + pattern->leftLen;
1028 word = cp + pattern->leftLen;
1029 if (wordLen == 0 || (pattern->flags & VAR_SUB_GLOBAL) == 0){
1038 Buf_AddByte(buf, (Byte)' ');
1040 Buf_AddBytes(buf, wordLen, (Byte *)word);
1043 * If added characters to the buffer, need to add a space
1044 * before we add any more. If we didn't add any, just return
1045 * the previous value of addSpace.
1047 return ((Buf_Size(buf) != origSize) || addSpace);
1050 * Common code for anchored substitutions:
1051 * addSpace was set TRUE if characters were added to the buffer.
1057 Buf_AddByte(buf, (Byte)' ');
1059 Buf_AddBytes(buf, wordLen, (Byte *)word);
1064 *-----------------------------------------------------------------------
1066 * Print the error caused by a regcomp or regexec call.
1072 * An error gets printed.
1074 *-----------------------------------------------------------------------
1077 VarREError(err, pat, str)
1085 errlen = regerror(err, pat, 0, 0);
1086 errbuf = emalloc(errlen);
1087 regerror(err, pat, errbuf, errlen);
1088 Error("%s: %s", str, errbuf);
1094 *-----------------------------------------------------------------------
1095 * VarRESubstitute --
1096 * Perform a regex substitution on the given word, placing the
1097 * result in the passed buffer.
1100 * TRUE if a space is needed before more characters are added.
1105 *-----------------------------------------------------------------------
1108 VarRESubstitute(word, addSpace, buf, patternp)
1112 ClientData patternp;
1121 #define MAYBE_ADD_SPACE() \
1122 if (addSpace && !added) \
1123 Buf_AddByte(buf, ' '); \
1130 if ((pat->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) ==
1131 (VAR_SUB_ONE|VAR_SUB_MATCHED))
1135 xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
1140 pat->flags |= VAR_SUB_MATCHED;
1141 if (pat->matches[0].rm_so > 0) {
1143 Buf_AddBytes(buf, pat->matches[0].rm_so, wp);
1146 for (rp = pat->replace; *rp; rp++) {
1147 if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
1149 Buf_AddByte(buf,rp[1]);
1152 else if ((*rp == '&') ||
1153 ((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
1171 if (n > pat->nsub) {
1172 Error("No subexpression %s", &errstr[0]);
1175 } else if ((pat->matches[n].rm_so == -1) &&
1176 (pat->matches[n].rm_eo == -1)) {
1177 Error("No match for subexpression %s", &errstr[0]);
1181 subbuf = wp + pat->matches[n].rm_so;
1182 sublen = pat->matches[n].rm_eo - pat->matches[n].rm_so;
1187 Buf_AddBytes(buf, sublen, subbuf);
1191 Buf_AddByte(buf, *rp);
1194 wp += pat->matches[0].rm_eo;
1195 if (pat->flags & VAR_SUB_GLOBAL) {
1196 flags |= REG_NOTBOL;
1197 if (pat->matches[0].rm_so == 0 && pat->matches[0].rm_eo == 0) {
1199 Buf_AddByte(buf, *wp);
1208 Buf_AddBytes(buf, strlen(wp), wp);
1212 VarREError(xrv, &pat->re, "Unexpected regex error");
1217 Buf_AddBytes(buf,strlen(wp),wp);
1221 return(addSpace||added);
1226 *-----------------------------------------------------------------------
1228 * Modify each of the words of the passed string using the given
1229 * function. Used to implement all modifiers.
1232 * A string of all the words modified appropriately.
1237 *-----------------------------------------------------------------------
1240 VarModify (str, modProc, datum)
1241 char *str; /* String whose words should be trimmed */
1242 /* Function to use to modify them */
1243 Boolean (*modProc) __P((char *, Boolean, Buffer, ClientData));
1244 ClientData datum; /* Datum to pass it */
1246 Buffer buf; /* Buffer for the new string */
1247 Boolean addSpace; /* TRUE if need to add a space to the
1248 * buffer before adding the trimmed
1250 char **av; /* word list [first word does not count] */
1256 av = brk_string(str, &ac, FALSE);
1258 for (i = 1; i < ac; i++)
1259 addSpace = (*modProc)(av[i], addSpace, buf, datum);
1261 Buf_AddByte (buf, '\0');
1262 str = (char *)Buf_GetAll (buf, (int *)NULL);
1263 Buf_Destroy (buf, FALSE);
1268 *-----------------------------------------------------------------------
1270 * Pass through the tstr looking for 1) escaped delimiters,
1271 * '$'s and backslashes (place the escaped character in
1272 * uninterpreted) and 2) unescaped $'s that aren't before
1273 * the delimiter (expand the variable substitution unless flags
1274 * has VAR_NOSUBST set).
1275 * Return the expanded string or NULL if the delimiter was missing
1276 * If pattern is specified, handle escaped ampersands, and replace
1277 * unescaped ampersands with the lhs of the pattern.
1280 * A string of all the words modified appropriately.
1281 * If length is specified, return the string length of the buffer
1282 * If flags is specified and the last character of the pattern is a
1283 * $ set the VAR_MATCH_END bit of flags.
1287 *-----------------------------------------------------------------------
1290 VarGetPattern(ctxt, err, tstr, delim, flags, length, pattern)
1297 VarPattern *pattern;
1300 Buffer buf = Buf_Init(0);
1305 #define IS_A_MATCH(cp, delim) \
1306 ((cp[0] == '\\') && ((cp[1] == delim) || \
1307 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
1310 * Skim through until the matching delimiter is found;
1311 * pick up variable substitutions on the way. Also allow
1312 * backslashes to quote the delimiter, $, and \, but don't
1313 * touch other backslashes.
1315 for (cp = *tstr; *cp && (*cp != delim); cp++) {
1316 if (IS_A_MATCH(cp, delim)) {
1317 Buf_AddByte(buf, (Byte) cp[1]);
1319 } else if (*cp == '$') {
1320 if (cp[1] == delim) {
1322 Buf_AddByte(buf, (Byte) *cp);
1325 * Unescaped $ at end of pattern => anchor
1328 *flags |= VAR_MATCH_END;
1330 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
1336 * If unescaped dollar sign not before the
1337 * delimiter, assume it's a variable
1338 * substitution and recurse.
1340 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1341 Buf_AddBytes(buf, strlen(cp2), (Byte *) cp2);
1348 if (*cp2 == '(' || *cp2 == '{') {
1350 * Find the end of this variable reference
1351 * and suck it in without further ado.
1352 * It will be interperated later.
1355 int want = (*cp2 == '(') ? ')' : '}';
1358 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
1359 if (cp2[-1] != '\\') {
1366 Buf_AddBytes(buf, cp2 - cp, (Byte *)cp);
1369 Buf_AddByte(buf, (Byte) *cp);
1373 else if (pattern && *cp == '&')
1374 Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
1376 Buf_AddByte(buf, (Byte) *cp);
1379 Buf_AddByte(buf, (Byte) '\0');
1388 cp = (char *) Buf_GetAll(buf, length);
1389 *length -= 1; /* Don't count the NULL */
1390 Buf_Destroy(buf, FALSE);
1397 *-----------------------------------------------------------------------
1399 * Quote shell meta-characters in the string
1407 *-----------------------------------------------------------------------
1415 /* This should cover most shells :-( */
1416 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
1418 buf = Buf_Init (MAKE_BSIZE);
1419 for (; *str; str++) {
1420 if (strchr(meta, *str) != NULL)
1421 Buf_AddByte(buf, (Byte)'\\');
1422 Buf_AddByte(buf, (Byte)*str);
1424 Buf_AddByte(buf, (Byte) '\0');
1425 str = (char *)Buf_GetAll (buf, (int *)NULL);
1426 Buf_Destroy (buf, FALSE);
1431 *-----------------------------------------------------------------------
1433 * Given the start of a variable invocation, extract the variable
1434 * name and find its value, then modify it according to the
1438 * The (possibly-modified) value of the variable or var_Error if the
1439 * specification is invalid. The length of the specification is
1440 * placed in *lengthPtr (for invalid specifications, this is just
1442 * A Boolean in *freePtr telling whether the returned string should
1443 * be freed by the caller.
1448 *-----------------------------------------------------------------------
1451 Var_Parse (str, ctxt, err, lengthPtr, freePtr)
1452 char *str; /* The string to parse */
1453 GNode *ctxt; /* The context for the variable */
1454 Boolean err; /* TRUE if undefined variables are an error */
1455 int *lengthPtr; /* OUT: The length of the specification */
1456 Boolean *freePtr; /* OUT: TRUE if caller should free result */
1458 register char *tstr; /* Pointer into str */
1459 Var *v; /* Variable in invocation */
1460 char *cp; /* Secondary pointer into str (place marker
1462 Boolean haveModifier;/* TRUE if have modifiers for the variable */
1463 register char endc; /* Ending character when variable in parens
1465 register char startc=0; /* Starting character when variable in parens
1467 int cnt; /* Used to count brace pairs when variable in
1468 * in parens or braces */
1471 Boolean dynamic; /* TRUE if the variable is local and we're
1472 * expanding it in a non-local context. This
1473 * is done to support dynamic sources. The
1474 * result is just the invocation, unaltered */
1475 int vlen; /* length of variable name, after embedded variable
1482 if (str[1] != '(' && str[1] != '{') {
1484 * If it's not bounded by braces of some sort, life is much simpler.
1485 * We just need to check for the first character and return the
1486 * value if it exists.
1493 v = VarFind (name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1494 if (v == (Var *)NIL) {
1497 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
1499 * If substituting a local variable in a non-local context,
1500 * assume it's for dynamic source stuff. We have to handle
1501 * this specially and return the longhand for the variable
1502 * with the dollar sign escaped so it makes it back to the
1503 * caller. Only four of the local variables are treated
1504 * specially as they are the only four that will be set
1505 * when dynamic sources are expanded.
1507 /* XXX: It looks like $% and $! are reversed here */
1510 return("$(.TARGET)");
1512 return("$(.ARCHIVE)");
1514 return("$(.PREFIX)");
1516 return("$(.MEMBER)");
1522 return (err ? var_Error : varNoError);
1524 haveModifier = FALSE;
1529 /* build up expanded variable name in this buffer */
1530 Buffer buf = Buf_Init(MAKE_BSIZE);
1533 endc = startc == '(' ? ')' : '}';
1536 * Skip to the end character or a colon, whichever comes first,
1537 * replacing embedded variables as we go.
1539 for (tstr = str + 2; *tstr != '\0' && *tstr != endc && *tstr != ':'; tstr++)
1543 char* rval = Var_Parse(tstr, ctxt, err, &rlen, &rfree);
1545 if (rval == var_Error) {
1546 Fatal("Error expanding embedded variable.");
1547 } else if (rval != NULL) {
1548 Buf_AddBytes(buf, strlen(rval), (Byte *) rval);
1554 Buf_AddByte(buf, (Byte) *tstr);
1556 if (*tstr == '\0') {
1558 * If we never did find the end character, return NULL
1559 * right now, setting the length to be the distance to
1560 * the end of the string, since that's what make does.
1562 *lengthPtr = tstr - str;
1566 haveModifier = (*tstr == ':');
1569 Buf_AddByte(buf, (Byte) '\0');
1570 str = Buf_GetAll(buf, NULL);
1573 v = VarFind (str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1574 if ((v == (Var *)NIL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
1575 (vlen == 2) && (str[1] == 'F' || str[1] == 'D'))
1578 * Check for bogus D and F forms of local variables since we're
1579 * in a local context and the name is the right length.
1593 * Well, it's local -- go look for it.
1597 v = VarFind(vname, ctxt, 0);
1599 if (v != (Var *)NIL && !haveModifier) {
1601 * No need for nested expansion or anything, as we're
1602 * the only one who sets these things and we sure don't
1603 * put nested invocations in them...
1605 val = (char *)Buf_GetAll(v->val, (int *)NULL);
1607 if (str[1] == 'D') {
1608 val = VarModify(val, VarHead, (ClientData)0);
1610 val = VarModify(val, VarTail, (ClientData)0);
1613 * Resulting string is dynamically allocated, so
1614 * tell caller to free it.
1617 *lengthPtr = tstr-start+1;
1619 Buf_Destroy(buf, TRUE);
1627 if (v == (Var *)NIL) {
1629 (((vlen == 2) && (str[1] == 'F' ||
1630 str[1] == 'D')))) &&
1631 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1634 * If substituting a local variable in a non-local context,
1635 * assume it's for dynamic source stuff. We have to handle
1636 * this specially and return the longhand for the variable
1637 * with the dollar sign escaped so it makes it back to the
1638 * caller. Only four of the local variables are treated
1639 * specially as they are the only four that will be set
1640 * when dynamic sources are expanded.
1650 } else if ((vlen > 2) && (str[0] == '.') &&
1651 isupper((unsigned char) str[1]) &&
1652 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1657 if ((strncmp(str, ".TARGET", len) == 0) ||
1658 (strncmp(str, ".ARCHIVE", len) == 0) ||
1659 (strncmp(str, ".PREFIX", len) == 0) ||
1660 (strncmp(str, ".MEMBER", len) == 0))
1666 if (!haveModifier) {
1668 * No modifiers -- have specification length so we can return
1671 *lengthPtr = tstr - start + 1;
1674 str = emalloc(*lengthPtr + 1);
1675 strncpy(str, start, *lengthPtr);
1676 str[*lengthPtr] = '\0';
1678 Buf_Destroy(buf, TRUE);
1681 Buf_Destroy(buf, TRUE);
1682 return (err ? var_Error : varNoError);
1686 * Still need to get to the end of the variable specification,
1687 * so kludge up a Var structure for the modifications
1689 v = (Var *) emalloc(sizeof(Var));
1691 v->val = Buf_Init(1);
1692 v->flags = VAR_JUNK;
1695 Buf_Destroy(buf, TRUE);
1698 if (v->flags & VAR_IN_USE) {
1699 Fatal("Variable %s is recursive.", v->name);
1702 v->flags |= VAR_IN_USE;
1705 * Before doing any modification, we have to make sure the value
1706 * has been fully expanded. If it looks like recursion might be
1707 * necessary (there's a dollar sign somewhere in the variable's value)
1708 * we just call Var_Subst to do any other substitutions that are
1709 * necessary. Note that the value returned by Var_Subst will have
1710 * been dynamically-allocated, so it will need freeing when we
1713 str = (char *)Buf_GetAll(v->val, (int *)NULL);
1714 if (strchr (str, '$') != (char *)NULL) {
1715 str = Var_Subst(NULL, str, ctxt, err);
1719 v->flags &= ~VAR_IN_USE;
1722 * Now we need to apply any modifiers the user wants applied.
1724 * :M<pattern> words which match the given <pattern>.
1725 * <pattern> is of the standard file
1727 * :S<d><pat1><d><pat2><d>[g]
1728 * Substitute <pat2> for <pat1> in the value
1729 * :C<d><pat1><d><pat2><d>[g]
1730 * Substitute <pat2> for regex <pat1> in the value
1731 * :H Substitute the head of each word
1732 * :T Substitute the tail of each word
1733 * :E Substitute the extension (minus '.') of
1735 * :R Substitute the root of each word
1736 * (pathname minus the suffix).
1737 * :lhs=rhs Like :S, but the rhs goes to the end of
1739 * :U Converts variable to upper-case.
1740 * :L Converts variable to lower-case.
1742 if ((str != (char *)NULL) && haveModifier) {
1744 * Skip initial colon while putting it back.
1747 while (*tstr != endc) {
1748 char *newStr; /* New value to return */
1749 char termc; /* Character which terminated scan */
1752 printf("Applying :%c to \"%s\"\n", *tstr, str);
1756 if (tstr[1] == endc || tstr[1] == ':') {
1758 buf = Buf_Init(MAKE_BSIZE);
1759 for (cp = str; *cp ; cp++)
1760 Buf_AddByte(buf, (Byte) toupper(*cp));
1762 Buf_AddByte(buf, (Byte) '\0');
1763 newStr = (char *) Buf_GetAll(buf, (int *) NULL);
1764 Buf_Destroy(buf, FALSE);
1772 if (tstr[1] == endc || tstr[1] == ':') {
1774 buf = Buf_Init(MAKE_BSIZE);
1775 for (cp = str; *cp ; cp++)
1776 Buf_AddByte(buf, (Byte) tolower(*cp));
1778 Buf_AddByte(buf, (Byte) '\0');
1779 newStr = (char *) Buf_GetAll(buf, (int *) NULL);
1780 Buf_Destroy(buf, FALSE);
1796 *cp != '\0' && *cp != ':' && *cp != endc;
1799 if (*cp == '\\' && (cp[1] == ':' || cp[1] == endc)){
1808 * Need to compress the \:'s out of the pattern, so
1809 * allocate enough room to hold the uncompressed
1810 * pattern (note that cp started at tstr+1, so
1811 * cp - tstr takes the null byte into account) and
1812 * compress the pattern into the space.
1814 pattern = emalloc(cp - tstr);
1815 for (cp2 = pattern, cp = tstr + 1;
1819 if ((*cp == '\\') &&
1820 (cp[1] == ':' || cp[1] == endc)) {
1829 if (*tstr == 'M' || *tstr == 'm') {
1830 newStr = VarModify(str, VarMatch, (ClientData)pattern);
1832 newStr = VarModify(str, VarNoMatch,
1833 (ClientData)pattern);
1843 register char delim;
1844 Buffer buf; /* Buffer for patterns */
1851 * If pattern begins with '^', it is anchored to the
1852 * start of the word -- skip over it and flag pattern.
1855 pattern.flags |= VAR_MATCH_START;
1862 * Pass through the lhs looking for 1) escaped delimiters,
1863 * '$'s and backslashes (place the escaped character in
1864 * uninterpreted) and 2) unescaped $'s that aren't before
1865 * the delimiter (expand the variable substitution).
1866 * The result is left in the Buffer buf.
1868 for (cp = tstr; *cp != '\0' && *cp != delim; cp++) {
1869 if ((*cp == '\\') &&
1870 ((cp[1] == delim) ||
1874 Buf_AddByte(buf, (Byte)cp[1]);
1876 } else if (*cp == '$') {
1877 if (cp[1] != delim) {
1879 * If unescaped dollar sign not before the
1880 * delimiter, assume it's a variable
1881 * substitution and recurse.
1887 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1888 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
1895 * Unescaped $ at end of pattern => anchor
1898 pattern.flags |= VAR_MATCH_END;
1901 Buf_AddByte(buf, (Byte)*cp);
1905 Buf_AddByte(buf, (Byte)'\0');
1908 * If lhs didn't end with the delimiter, complain and
1912 *lengthPtr = cp - start + 1;
1916 Buf_Destroy(buf, TRUE);
1917 Error("Unclosed substitution for %s (%c missing)",
1923 * Fetch pattern and destroy buffer, but preserve the data
1924 * in it, since that's our lhs. Note that Buf_GetAll
1925 * will return the actual number of bytes, which includes
1926 * the null byte, so we have to decrement the length by
1929 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1931 Buf_Destroy(buf, FALSE);
1934 * Now comes the replacement string. Three things need to
1935 * be done here: 1) need to compress escaped delimiters and
1936 * ampersands and 2) need to replace unescaped ampersands
1937 * with the l.h.s. (since this isn't regexp, we can do
1938 * it right here) and 3) expand any variable substitutions.
1943 for (cp = tstr; *cp != '\0' && *cp != delim; cp++) {
1944 if ((*cp == '\\') &&
1945 ((cp[1] == delim) ||
1950 Buf_AddByte(buf, (Byte)cp[1]);
1952 } else if ((*cp == '$') && (cp[1] != delim)) {
1957 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1958 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
1963 } else if (*cp == '&') {
1964 Buf_AddBytes(buf, pattern.leftLen,
1965 (Byte *)pattern.lhs);
1967 Buf_AddByte(buf, (Byte)*cp);
1971 Buf_AddByte(buf, (Byte)'\0');
1974 * If didn't end in delimiter character, complain
1977 *lengthPtr = cp - start + 1;
1981 Buf_Destroy(buf, TRUE);
1982 Error("Unclosed substitution for %s (%c missing)",
1987 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1989 Buf_Destroy(buf, FALSE);
1992 * Check for global substitution. If 'g' after the final
1993 * delimiter, substitution is global and is marked that
1998 pattern.flags |= VAR_SUB_GLOBAL;
2003 newStr = VarModify(str, VarSubstitute,
2004 (ClientData)&pattern);
2006 * Free the two strings.
2014 VarREPattern pattern;
2024 if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
2025 NULL, NULL)) == NULL) {
2026 /* was: goto cleanup */
2027 *lengthPtr = cp - start + 1;
2031 Error("Unclosed substitution for %s (%c missing)",
2036 if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
2037 delim, NULL, NULL, NULL)) == NULL){
2040 /* was: goto cleanup */
2041 *lengthPtr = cp - start + 1;
2045 Error("Unclosed substitution for %s (%c missing)",
2053 pattern.flags |= VAR_SUB_GLOBAL;
2056 pattern.flags |= VAR_SUB_ONE;
2064 error = regcomp(&pattern.re, re, REG_EXTENDED);
2067 *lengthPtr = cp - start + 1;
2068 VarREError(error, &pattern.re, "RE substitution error");
2069 free(pattern.replace);
2073 pattern.nsub = pattern.re.re_nsub + 1;
2074 if (pattern.nsub < 1)
2076 if (pattern.nsub > 10)
2078 pattern.matches = emalloc(pattern.nsub *
2079 sizeof(regmatch_t));
2080 newStr = VarModify(str, VarRESubstitute,
2081 (ClientData) &pattern);
2082 regfree(&pattern.re);
2083 free(pattern.replace);
2084 free(pattern.matches);
2088 if (tstr[1] == endc || tstr[1] == ':') {
2089 newStr = VarQuote (str);
2096 if (tstr[1] == endc || tstr[1] == ':') {
2097 newStr = VarModify (str, VarTail, (ClientData)0);
2104 if (tstr[1] == endc || tstr[1] == ':') {
2105 newStr = VarModify (str, VarHead, (ClientData)0);
2112 if (tstr[1] == endc || tstr[1] == ':') {
2113 newStr = VarModify (str, VarSuffix, (ClientData)0);
2120 if (tstr[1] == endc || tstr[1] == ':') {
2121 newStr = VarModify (str, VarRoot, (ClientData)0);
2129 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
2131 newStr = Cmd_Exec (str, &err);
2144 * This can either be a bogus modifier or a System-V
2145 * substitution command.
2153 * First we make a pass through the string trying
2154 * to verify it is a SYSV-make-style translation:
2155 * it must be: <string1>=<string2>)
2159 while (*cp != '\0' && cnt) {
2162 /* continue looking for endc */
2164 else if (*cp == endc)
2166 else if (*cp == startc)
2171 if (*cp == endc && eqFound) {
2174 * Now we break this sucker into the lhs and
2175 * rhs. We must null terminate them of course.
2177 for (cp = tstr; *cp != '='; cp++)
2180 pattern.leftLen = cp - tstr;
2188 else if (*cp == startc)
2193 pattern.rightLen = cp - pattern.rhs;
2197 * SYSV modifications happen through the whole
2198 * string. Note the pattern is anchored at the end.
2200 newStr = VarModify(str, VarSYSVMatch,
2201 (ClientData)&pattern);
2204 * Restore the nulled characters
2206 pattern.lhs[pattern.leftLen] = '=';
2207 pattern.rhs[pattern.rightLen] = endc;
2212 Error ("Unknown modifier '%c'\n", *tstr);
2214 *cp != ':' && *cp != endc && *cp != '\0';
2223 printf("Result is \"%s\"\n", newStr);
2230 if (str != var_Error) {
2235 if (termc == '\0') {
2236 Error("Unclosed variable specification for %s", v->name);
2237 } else if (termc == ':') {
2244 *lengthPtr = tstr - start + 1;
2246 *lengthPtr = tstr - start + 1;
2250 if (v->flags & VAR_FROM_ENV) {
2251 Boolean destroy = FALSE;
2253 if (str != (char *)Buf_GetAll(v->val, (int *)NULL)) {
2257 * Returning the value unmodified, so tell the caller to free
2262 Buf_Destroy(v->val, destroy);
2264 } else if (v->flags & VAR_JUNK) {
2266 * Perform any free'ing needed and set *freePtr to FALSE so the caller
2267 * doesn't try to free a static pointer.
2273 Buf_Destroy(v->val, TRUE);
2276 str = emalloc(*lengthPtr + 1);
2277 strncpy(str, start, *lengthPtr);
2278 str[*lengthPtr] = '\0';
2281 str = err ? var_Error : varNoError;
2288 *-----------------------------------------------------------------------
2290 * Substitute for all variables in the given string in the given context
2291 * If undefErr is TRUE, Parse_Error will be called when an undefined
2292 * variable is encountered.
2295 * The resulting string.
2298 * None. The old string must be freed by the caller
2299 *-----------------------------------------------------------------------
2302 Var_Subst (var, str, ctxt, undefErr)
2303 char *var; /* Named variable || NULL for all */
2304 char *str; /* the string in which to substitute */
2305 GNode *ctxt; /* the context wherein to find variables */
2306 Boolean undefErr; /* TRUE if undefineds are an error */
2308 Buffer buf; /* Buffer for forming things */
2309 char *val; /* Value to substitute for a variable */
2310 int length; /* Length of the variable invocation */
2311 Boolean doFree; /* Set true if val should be freed */
2312 static Boolean errorReported; /* Set true if an error has already
2313 * been reported to prevent a plethora
2314 * of messages when recursing */
2316 buf = Buf_Init (MAKE_BSIZE);
2317 errorReported = FALSE;
2320 if (var == NULL && (*str == '$') && (str[1] == '$')) {
2322 * A dollar sign may be escaped either with another dollar sign.
2323 * In such a case, we skip over the escape character and store the
2324 * dollar sign into the buffer directly.
2327 Buf_AddByte(buf, (Byte)*str);
2329 } else if (*str != '$') {
2331 * Skip as many characters as possible -- either to the end of
2332 * the string or to the next dollar sign (variable invocation).
2336 for (cp = str++; *str != '$' && *str != '\0'; str++)
2338 Buf_AddBytes(buf, str - cp, (Byte *)cp);
2343 if (str[1] != '(' && str[1] != '{') {
2344 if (str[1] != *var) {
2345 Buf_AddBytes(buf, 2, (Byte *) str);
2357 * Scan up to the end of the variable name.
2359 for (p = &str[2]; *p &&
2360 *p != ':' && *p != ')' && *p != '}'; p++)
2364 * A variable inside the variable. We cannot expand
2365 * the external variable yet, so we try again with
2369 Buf_AddBytes(buf, p - str, (Byte *) str);
2374 if (strncmp(var, str + 2, p - str - 2) != 0 ||
2375 var[p - str - 2] != '\0') {
2377 * Not the variable we want to expand, scan
2378 * until the next variable
2380 for (;*p != '$' && *p != '\0'; p++)
2382 Buf_AddBytes(buf, p - str, (Byte *) str);
2395 val = Var_Parse (str, ctxt, undefErr, &length, &doFree);
2398 * When we come down here, val should either point to the
2399 * value of this variable, suitably modified, or be NULL.
2400 * Length should be the total length of the potential
2401 * variable invocation (from $ to end character...)
2403 if (val == var_Error || val == varNoError) {
2405 * If performing old-time variable substitution, skip over
2406 * the variable and continue with the substitution. Otherwise,
2407 * store the dollar sign and advance str so we continue with
2412 } else if (undefErr) {
2414 * If variable is undefined, complain and skip the
2415 * variable. The complaint will stop us from doing anything
2416 * when the file is parsed.
2418 if (!errorReported) {
2419 Parse_Error (PARSE_FATAL,
2420 "Undefined variable \"%.*s\"",length,str);
2423 errorReported = TRUE;
2425 Buf_AddByte (buf, (Byte)*str);
2430 * We've now got a variable structure to store in. But first,
2431 * advance the string pointer.
2436 * Copy all the characters from the variable value straight
2437 * into the new string.
2439 Buf_AddBytes (buf, strlen (val), (Byte *)val);
2441 free ((Address)val);
2447 Buf_AddByte (buf, '\0');
2448 str = (char *)Buf_GetAll (buf, (int *)NULL);
2449 Buf_Destroy (buf, FALSE);
2454 *-----------------------------------------------------------------------
2456 * Return the tail from each of a list of words. Used to set the
2457 * System V local variables.
2460 * The resulting string.
2465 *-----------------------------------------------------------------------
2469 char *file; /* Filename to modify */
2471 return(VarModify(file, VarTail, (ClientData)0));
2475 *-----------------------------------------------------------------------
2477 * Find the leading components of a (list of) filename(s).
2478 * XXX: VarHead does not replace foo by ., as (sun) System V make
2482 * The leading components.
2487 *-----------------------------------------------------------------------
2491 char *file; /* Filename to manipulate */
2493 return(VarModify(file, VarHead, (ClientData)0));
2497 *-----------------------------------------------------------------------
2499 * Initialize the module
2505 * The VAR_CMD and VAR_GLOBAL contexts are created
2506 *-----------------------------------------------------------------------
2511 VAR_GLOBAL = Targ_NewGN ("Global");
2512 VAR_CMD = Targ_NewGN ("Command");
2513 allVars = Lst_Init(FALSE);
2521 Lst_Destroy(allVars, VarDelete);
2525 /****************** PRINT DEBUGGING INFO *****************/
2527 VarPrintVar (vp, dummy)
2531 Var *v = (Var *) vp;
2532 printf ("%-16s = %s\n", v->name, (char *) Buf_GetAll(v->val, (int *)NULL));
2533 return (dummy ? 0 : 0);
2537 *-----------------------------------------------------------------------
2539 * print all variables in a context
2540 *-----------------------------------------------------------------------
2546 Lst_ForEach (ctxt->context, VarPrintVar, (ClientData) 0);