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
41 static char sccsid[] = "@(#)var.c 8.3 (Berkeley) 3/19/94";
43 static const char rcsid[] =
44 "$FreeBSD: src/usr.bin/make/var.c,v 1.16.2.3 2002/02/27 14:18:57 cjc Exp $";
50 * Variable-handling functions
53 * Var_Set Set the value of a variable in the given
54 * context. The variable is created if it doesn't
55 * yet exist. The value and variable name need not
58 * Var_Append Append more characters to an existing variable
59 * in the given context. The variable needn't
60 * exist already -- it will be created if it doesn't.
61 * A space is placed between the old value and the
64 * Var_Exists See if a variable exists.
66 * Var_Value Return the value of a variable in a context or
67 * NULL if the variable is undefined.
69 * Var_Subst Substitute named variable, or all variables if
70 * NULL in a string using
71 * the given context as the top-most one. If the
72 * third argument is non-zero, Parse_Error is
73 * called if any variables are undefined.
75 * Var_Parse Parse a variable expansion from a string and
76 * return the result and the number of characters
79 * Var_Delete Delete a variable in a context.
81 * Var_Init Initialize this module.
84 * Var_Dump Print out all variables defined in the given
87 * XXX: There's a lot of duplication in these functions.
91 #include <sys/types.h>
98 * This is a harmless return value for Var_Parse that can be used by Var_Subst
99 * to determine if there was an error in parsing -- easier than returning
100 * a flag, as things outside this module don't give a hoot.
102 char var_Error[] = "";
105 * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
106 * set false. Why not just use a constant? Well, gcc likes to condense
107 * identical string instances...
109 static char varNoError[] = "";
112 * Internally, variables are contained in four different contexts.
113 * 1) the environment. They may not be changed. If an environment
114 * variable is appended-to, the result is placed in the global
116 * 2) the global context. Variables set in the Makefile are located in
117 * the global context. It is the penultimate context searched when
119 * 3) the command-line context. All variables set on the command line
120 * are placed in this context. They are UNALTERABLE once placed here.
121 * 4) the local context. Each target has associated with it a context
122 * list. On this list are located the structures describing such
123 * local variables as $(@) and $(*)
124 * The four contexts are searched in the reverse order from which they are
127 GNode *VAR_GLOBAL; /* variables from the makefile */
128 GNode *VAR_CMD; /* variables defined on the command-line */
130 static Lst allVars; /* List of all variables */
132 #define FIND_CMD 0x1 /* look in VAR_CMD when searching */
133 #define FIND_GLOBAL 0x2 /* look in VAR_GLOBAL as well */
134 #define FIND_ENV 0x4 /* look in the environment also */
137 char *name; /* the variable's name */
138 Buffer val; /* its value */
139 int flags; /* miscellaneous status flags */
140 #define VAR_IN_USE 1 /* Variable's value currently being used.
141 * Used to avoid recursion */
142 #define VAR_FROM_ENV 2 /* Variable comes from the environment */
143 #define VAR_JUNK 4 /* Variable is a junk variable that
144 * should be destroyed when done with
145 * it. Used by Var_Parse for undefined,
146 * modified variables */
149 /* Var*Pattern flags */
150 #define VAR_SUB_GLOBAL 0x01 /* Apply substitution globally */
151 #define VAR_SUB_ONE 0x02 /* Apply substitution to one word */
152 #define VAR_SUB_MATCHED 0x04 /* There was a match */
153 #define VAR_MATCH_START 0x08 /* Match at start of word */
154 #define VAR_MATCH_END 0x10 /* Match at end of word */
155 #define VAR_NOSUBST 0x20 /* don't expand vars in VarGetPattern */
158 char *lhs; /* String to match */
159 int leftLen; /* Length of string */
160 char *rhs; /* Replacement string (w/ &'s removed) */
161 int rightLen; /* Length of replacement */
173 static int VarCmp __P((ClientData, ClientData));
174 static Var *VarFind __P((char *, GNode *, int));
175 static void VarAdd __P((char *, char *, GNode *));
176 static void VarDelete __P((ClientData));
177 static Boolean VarHead __P((char *, Boolean, Buffer, ClientData));
178 static Boolean VarTail __P((char *, Boolean, Buffer, ClientData));
179 static Boolean VarSuffix __P((char *, Boolean, Buffer, ClientData));
180 static Boolean VarRoot __P((char *, Boolean, Buffer, ClientData));
181 static Boolean VarMatch __P((char *, Boolean, Buffer, ClientData));
183 static Boolean VarSYSVMatch __P((char *, Boolean, Buffer, ClientData));
185 static Boolean VarNoMatch __P((char *, Boolean, Buffer, ClientData));
186 static void VarREError __P((int, regex_t *, const char *));
187 static Boolean VarRESubstitute __P((char *, Boolean, Buffer, ClientData));
188 static Boolean VarSubstitute __P((char *, Boolean, Buffer, ClientData));
189 static char *VarGetPattern __P((GNode *, int, char **, int, int *, int *,
191 static char *VarQuote __P((char *));
192 static char *VarModify __P((char *, Boolean (*)(char *, Boolean, Buffer,
195 static int VarPrintVar __P((ClientData, ClientData));
198 *-----------------------------------------------------------------------
200 * See if the given variable matches the named one. Called from
201 * Lst_Find when searching for a variable of a given name.
204 * 0 if they match. non-zero otherwise.
208 *-----------------------------------------------------------------------
212 ClientData v; /* VAR structure to compare */
213 ClientData name; /* name to look for */
215 return (strcmp ((char *) name, ((Var *) v)->name));
219 *-----------------------------------------------------------------------
221 * Find the given variable in the given context and any other contexts
225 * A pointer to the structure describing the desired variable or
226 * NIL if the variable does not exist.
230 *-----------------------------------------------------------------------
233 VarFind (name, ctxt, flags)
234 char *name; /* name to find */
235 GNode *ctxt; /* context in which to find it */
236 int flags; /* FIND_GLOBAL set means to look in the
237 * VAR_GLOBAL context as well.
238 * FIND_CMD set means to look in the VAR_CMD
240 * FIND_ENV set means to look in the
243 Boolean localCheckEnvFirst;
248 * If the variable name begins with a '.', it could very well be one of
249 * the local ones. We check the name against all the local variables
250 * and substitute the short version in for 'name' if it matches one of
253 if (*name == '.' && isupper((unsigned char) name[1]))
256 if (!strcmp(name, ".ALLSRC"))
258 if (!strcmp(name, ".ARCHIVE"))
262 if (!strcmp(name, ".IMPSRC"))
266 if (!strcmp(name, ".MEMBER"))
270 if (!strcmp(name, ".OODATE"))
274 if (!strcmp(name, ".PREFIX"))
278 if (!strcmp(name, ".TARGET"))
284 * Note whether this is one of the specific variables we were told through
285 * the -E flag to use environment-variable-override for.
287 if (Lst_Find (envFirstVars, (ClientData)name,
288 (int (*)(ClientData, ClientData)) strcmp) != NILLNODE)
290 localCheckEnvFirst = TRUE;
292 localCheckEnvFirst = FALSE;
296 * First look for the variable in the given context. If it's not there,
297 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
298 * depending on the FIND_* flags in 'flags'
300 var = Lst_Find (ctxt->context, (ClientData)name, VarCmp);
302 if ((var == NILLNODE) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
303 var = Lst_Find (VAR_CMD->context, (ClientData)name, VarCmp);
305 if ((var == NILLNODE) && (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL) &&
306 !checkEnvFirst && !localCheckEnvFirst)
308 var = Lst_Find (VAR_GLOBAL->context, (ClientData)name, VarCmp);
310 if ((var == NILLNODE) && (flags & FIND_ENV)) {
313 if ((env = getenv (name)) != NULL) {
316 v = (Var *) emalloc(sizeof(Var));
317 v->name = estrdup(name);
321 v->val = Buf_Init(len);
322 Buf_AddBytes(v->val, len, (Byte *)env);
324 v->flags = VAR_FROM_ENV;
326 } else if ((checkEnvFirst || localCheckEnvFirst) &&
327 (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL))
329 var = Lst_Find (VAR_GLOBAL->context, (ClientData)name, VarCmp);
330 if (var == NILLNODE) {
331 return ((Var *) NIL);
333 return ((Var *)Lst_Datum(var));
338 } else if (var == NILLNODE) {
339 return ((Var *) NIL);
341 return ((Var *) Lst_Datum (var));
346 *-----------------------------------------------------------------------
348 * Add a new variable of name name and value val to the given context
354 * The new variable is placed at the front of the given context
355 * The name and val arguments are duplicated so they may
357 *-----------------------------------------------------------------------
360 VarAdd (name, val, ctxt)
361 char *name; /* name of variable to add */
362 char *val; /* value to set it to */
363 GNode *ctxt; /* context in which to set it */
368 v = (Var *) emalloc (sizeof (Var));
370 v->name = estrdup (name);
372 len = val ? strlen(val) : 0;
373 v->val = Buf_Init(len+1);
374 Buf_AddBytes(v->val, len, (Byte *)val);
378 (void) Lst_AtFront (ctxt->context, (ClientData)v);
379 (void) Lst_AtEnd (allVars, (ClientData) v);
381 printf("%s:%s = %s\n", ctxt->name, name, val);
387 *-----------------------------------------------------------------------
389 * Delete a variable and all the space associated with it.
396 *-----------------------------------------------------------------------
404 Buf_Destroy(v->val, TRUE);
411 *-----------------------------------------------------------------------
413 * Remove a variable from a context.
419 * The Var structure is removed and freed.
421 *-----------------------------------------------------------------------
424 Var_Delete(name, ctxt)
431 printf("%s:delete %s\n", ctxt->name, name);
433 ln = Lst_Find(ctxt->context, (ClientData)name, VarCmp);
434 if (ln != NILLNODE) {
437 v = (Var *)Lst_Datum(ln);
438 Lst_Remove(ctxt->context, ln);
439 ln = Lst_Member(allVars, v);
440 Lst_Remove(allVars, ln);
441 VarDelete((ClientData) v);
446 *-----------------------------------------------------------------------
448 * Set the variable name to the value val in the given context.
454 * If the variable doesn't yet exist, a new record is created for it.
455 * Else the old value is freed and the new one stuck in its place
458 * The variable is searched for only in its context before being
459 * created in that context. I.e. if the context is VAR_GLOBAL,
460 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
461 * VAR_CMD->context is searched. This is done to avoid the literally
462 * thousands of unnecessary strcmp's that used to be done to
463 * set, say, $(@) or $(<).
464 *-----------------------------------------------------------------------
467 Var_Set (name, val, ctxt)
468 char *name; /* name of variable to set */
469 char *val; /* value to give to the variable */
470 GNode *ctxt; /* context in which to set it */
475 * We only look for a variable in the given context since anything set
476 * here will override anything in a lower context, so there's not much
477 * point in searching them all just to save a bit of memory...
479 v = VarFind (name, ctxt, 0);
480 if (v == (Var *) NIL) {
481 VarAdd (name, val, ctxt);
483 Buf_Discard(v->val, Buf_Size(v->val));
484 Buf_AddBytes(v->val, strlen(val), (Byte *)val);
487 printf("%s:%s = %s\n", ctxt->name, name, val);
491 * Any variables given on the command line are automatically exported
492 * to the environment (as per POSIX standard)
494 if (ctxt == VAR_CMD) {
495 setenv(name, val, 1);
500 *-----------------------------------------------------------------------
502 * The variable of the given name has the given value appended to it in
509 * If the variable doesn't exist, it is created. Else the strings
510 * are concatenated (with a space in between).
513 * Only if the variable is being sought in the global context is the
514 * environment searched.
515 * XXX: Knows its calling circumstances in that if called with ctxt
516 * an actual target, it will only search that context since only
517 * a local variable could be being appended to. This is actually
518 * a big win and must be tolerated.
519 *-----------------------------------------------------------------------
522 Var_Append (name, val, ctxt)
523 char *name; /* Name of variable to modify */
524 char *val; /* String to append to it */
525 GNode *ctxt; /* Context in which this should occur */
529 v = VarFind (name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
531 if (v == (Var *) NIL) {
532 VarAdd (name, val, ctxt);
534 Buf_AddByte(v->val, (Byte)' ');
535 Buf_AddBytes(v->val, strlen(val), (Byte *)val);
538 printf("%s:%s = %s\n", ctxt->name, name,
539 (char *) Buf_GetAll(v->val, (int *)NULL));
542 if (v->flags & VAR_FROM_ENV) {
544 * If the original variable came from the environment, we
545 * have to install it in the global context (we could place
546 * it in the environment, but then we should provide a way to
547 * export other variables...)
549 v->flags &= ~VAR_FROM_ENV;
550 Lst_AtFront(ctxt->context, (ClientData)v);
556 *-----------------------------------------------------------------------
558 * See if the given variable exists.
561 * TRUE if it does, FALSE if it doesn't
566 *-----------------------------------------------------------------------
569 Var_Exists(name, ctxt)
570 char *name; /* Variable to find */
571 GNode *ctxt; /* Context in which to start search */
575 v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
577 if (v == (Var *)NIL) {
579 } else if (v->flags & VAR_FROM_ENV) {
581 Buf_Destroy(v->val, TRUE);
588 *-----------------------------------------------------------------------
590 * Return the value of the named variable in the given context
593 * The value if the variable exists, NULL if it doesn't
597 *-----------------------------------------------------------------------
600 Var_Value (name, ctxt, frp)
601 char *name; /* name to find */
602 GNode *ctxt; /* context in which to search for it */
607 v = VarFind (name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
609 if (v != (Var *) NIL) {
610 char *p = ((char *)Buf_GetAll(v->val, (int *)NULL));
611 if (v->flags & VAR_FROM_ENV) {
612 Buf_Destroy(v->val, FALSE);
618 return ((char *) NULL);
623 *-----------------------------------------------------------------------
625 * Remove the tail of the given word and place the result in the given
629 * TRUE if characters were added to the buffer (a space needs to be
630 * added to the buffer before the next word).
633 * The trimmed word is added to the buffer.
635 *-----------------------------------------------------------------------
638 VarHead (word, addSpace, buf, dummy)
639 char *word; /* Word to trim */
640 Boolean addSpace; /* True if need to add a space to the buffer
641 * before sticking in the head */
642 Buffer buf; /* Buffer in which to store it */
645 register char *slash;
647 slash = strrchr (word, '/');
648 if (slash != (char *)NULL) {
650 Buf_AddByte (buf, (Byte)' ');
653 Buf_AddBytes (buf, strlen (word), (Byte *)word);
658 * If no directory part, give . (q.v. the POSIX standard)
661 Buf_AddBytes(buf, 2, (Byte *)" .");
663 Buf_AddByte(buf, (Byte)'.');
666 return(dummy ? TRUE : TRUE);
670 *-----------------------------------------------------------------------
672 * Remove the head of the given word and place the result in the given
676 * TRUE if characters were added to the buffer (a space needs to be
677 * added to the buffer before the next word).
680 * The trimmed word is added to the buffer.
682 *-----------------------------------------------------------------------
685 VarTail (word, addSpace, buf, dummy)
686 char *word; /* Word to trim */
687 Boolean addSpace; /* TRUE if need to stick a space in the
688 * buffer before adding the tail */
689 Buffer buf; /* Buffer in which to store it */
692 register char *slash;
695 Buf_AddByte (buf, (Byte)' ');
698 slash = strrchr (word, '/');
699 if (slash != (char *)NULL) {
701 Buf_AddBytes (buf, strlen(slash), (Byte *)slash);
704 Buf_AddBytes (buf, strlen(word), (Byte *)word);
706 return (dummy ? TRUE : TRUE);
710 *-----------------------------------------------------------------------
712 * Place the suffix of the given word in the given buffer.
715 * TRUE if characters were added to the buffer (a space needs to be
716 * added to the buffer before the next word).
719 * The suffix from the word is placed in the buffer.
721 *-----------------------------------------------------------------------
724 VarSuffix (word, addSpace, buf, dummy)
725 char *word; /* Word to trim */
726 Boolean addSpace; /* TRUE if need to add a space before placing
727 * the suffix in the buffer */
728 Buffer buf; /* Buffer in which to store it */
733 dot = strrchr (word, '.');
734 if (dot != (char *)NULL) {
736 Buf_AddByte (buf, (Byte)' ');
739 Buf_AddBytes (buf, strlen (dot), (Byte *)dot);
743 return (dummy ? addSpace : addSpace);
747 *-----------------------------------------------------------------------
749 * Remove the suffix of the given word and place the result in the
753 * TRUE if characters were added to the buffer (a space needs to be
754 * added to the buffer before the next word).
757 * The trimmed word is added to the buffer.
759 *-----------------------------------------------------------------------
762 VarRoot (word, addSpace, buf, dummy)
763 char *word; /* Word to trim */
764 Boolean addSpace; /* TRUE if need to add a space to the buffer
765 * before placing the root in it */
766 Buffer buf; /* Buffer in which to store it */
772 Buf_AddByte (buf, (Byte)' ');
775 dot = strrchr (word, '.');
776 if (dot != (char *)NULL) {
778 Buf_AddBytes (buf, strlen (word), (Byte *)word);
781 Buf_AddBytes (buf, strlen(word), (Byte *)word);
783 return (dummy ? TRUE : TRUE);
787 *-----------------------------------------------------------------------
789 * Place the word in the buffer if it matches the given pattern.
790 * Callback function for VarModify to implement the :M modifier.
793 * TRUE if a space should be placed in the buffer before the next
797 * The word may be copied to the buffer.
799 *-----------------------------------------------------------------------
802 VarMatch (word, addSpace, buf, pattern)
803 char *word; /* Word to examine */
804 Boolean addSpace; /* TRUE if need to add a space to the
805 * buffer before adding the word, if it
807 Buffer buf; /* Buffer in which to store it */
808 ClientData pattern; /* Pattern the word must match */
810 if (Str_Match(word, (char *) pattern)) {
812 Buf_AddByte(buf, (Byte)' ');
815 Buf_AddBytes(buf, strlen(word), (Byte *)word);
822 *-----------------------------------------------------------------------
824 * Place the word in the buffer if it matches the given pattern.
825 * Callback function for VarModify to implement the System V %
829 * TRUE if a space should be placed in the buffer before the next
833 * The word may be copied to the buffer.
835 *-----------------------------------------------------------------------
838 VarSYSVMatch (word, addSpace, buf, patp)
839 char *word; /* Word to examine */
840 Boolean addSpace; /* TRUE if need to add a space to the
841 * buffer before adding the word, if it
843 Buffer buf; /* Buffer in which to store it */
844 ClientData patp; /* Pattern the word must match */
848 VarPattern *pat = (VarPattern *) patp;
851 Buf_AddByte(buf, (Byte)' ');
855 if ((ptr = Str_SYSVMatch(word, pat->lhs, &len)) != NULL)
856 Str_SYSVSubst(buf, pat->rhs, ptr, len);
858 Buf_AddBytes(buf, strlen(word), (Byte *) word);
866 *-----------------------------------------------------------------------
868 * Place the word in the buffer if it doesn't match the given pattern.
869 * Callback function for VarModify to implement the :N modifier.
872 * TRUE if a space should be placed in the buffer before the next
876 * The word may be copied to the buffer.
878 *-----------------------------------------------------------------------
881 VarNoMatch (word, addSpace, buf, pattern)
882 char *word; /* Word to examine */
883 Boolean addSpace; /* TRUE if need to add a space to the
884 * buffer before adding the word, if it
886 Buffer buf; /* Buffer in which to store it */
887 ClientData pattern; /* Pattern the word must match */
889 if (!Str_Match(word, (char *) pattern)) {
891 Buf_AddByte(buf, (Byte)' ');
894 Buf_AddBytes(buf, strlen(word), (Byte *)word);
901 *-----------------------------------------------------------------------
903 * Perform a string-substitution on the given word, placing the
904 * result in the passed buffer.
907 * TRUE if a space is needed before more characters are added.
912 *-----------------------------------------------------------------------
915 VarSubstitute (word, addSpace, buf, patternp)
916 char *word; /* Word to modify */
917 Boolean addSpace; /* True if space should be added before
918 * other characters */
919 Buffer buf; /* Buffer for result */
920 ClientData patternp; /* Pattern for substitution */
922 register int wordLen; /* Length of word */
923 register char *cp; /* General pointer */
924 VarPattern *pattern = (VarPattern *) patternp;
926 wordLen = strlen(word);
927 if (1) { /* substitute in each word of the variable */
929 * Break substitution down into simple anchored cases
930 * and if none of them fits, perform the general substitution case.
932 if ((pattern->flags & VAR_MATCH_START) &&
933 (strncmp(word, pattern->lhs, pattern->leftLen) == 0)) {
935 * Anchored at start and beginning of word matches pattern
937 if ((pattern->flags & VAR_MATCH_END) &&
938 (wordLen == pattern->leftLen)) {
940 * Also anchored at end and matches to the end (word
941 * is same length as pattern) add space and rhs only
942 * if rhs is non-null.
944 if (pattern->rightLen != 0) {
946 Buf_AddByte(buf, (Byte)' ');
949 Buf_AddBytes(buf, pattern->rightLen,
950 (Byte *)pattern->rhs);
952 } else if (pattern->flags & VAR_MATCH_END) {
954 * Doesn't match to end -- copy word wholesale
959 * Matches at start but need to copy in trailing characters
961 if ((pattern->rightLen + wordLen - pattern->leftLen) != 0){
963 Buf_AddByte(buf, (Byte)' ');
967 Buf_AddBytes(buf, pattern->rightLen, (Byte *)pattern->rhs);
968 Buf_AddBytes(buf, wordLen - pattern->leftLen,
969 (Byte *)(word + pattern->leftLen));
971 } else if (pattern->flags & VAR_MATCH_START) {
973 * Had to match at start of word and didn't -- copy whole word.
976 } else if (pattern->flags & VAR_MATCH_END) {
978 * Anchored at end, Find only place match could occur (leftLen
979 * characters from the end of the word) and see if it does. Note
980 * that because the $ will be left at the end of the lhs, we have
983 cp = word + (wordLen - pattern->leftLen);
985 (strncmp(cp, pattern->lhs, pattern->leftLen) == 0)) {
987 * Match found. If we will place characters in the buffer,
988 * add a space before hand as indicated by addSpace, then
989 * stuff in the initial, unmatched part of the word followed
990 * by the right-hand-side.
992 if (((cp - word) + pattern->rightLen) != 0) {
994 Buf_AddByte(buf, (Byte)' ');
998 Buf_AddBytes(buf, cp - word, (Byte *)word);
999 Buf_AddBytes(buf, pattern->rightLen, (Byte *)pattern->rhs);
1002 * Had to match at end and didn't. Copy entire word.
1008 * Pattern is unanchored: search for the pattern in the word using
1009 * String_FindSubstring, copying unmatched portions and the
1010 * right-hand-side for each match found, handling non-global
1011 * substitutions correctly, etc. When the loop is done, any
1012 * remaining part of the word (word and wordLen are adjusted
1013 * accordingly through the loop) is copied straight into the
1015 * addSpace is set FALSE as soon as a space is added to the
1018 register Boolean done;
1022 origSize = Buf_Size(buf);
1024 cp = Str_FindSubstring(word, pattern->lhs);
1025 if (cp != (char *)NULL) {
1026 if (addSpace && (((cp - word) + pattern->rightLen) != 0)){
1027 Buf_AddByte(buf, (Byte)' ');
1030 Buf_AddBytes(buf, cp-word, (Byte *)word);
1031 Buf_AddBytes(buf, pattern->rightLen, (Byte *)pattern->rhs);
1032 wordLen -= (cp - word) + pattern->leftLen;
1033 word = cp + pattern->leftLen;
1034 if (wordLen == 0 || (pattern->flags & VAR_SUB_GLOBAL) == 0){
1043 Buf_AddByte(buf, (Byte)' ');
1045 Buf_AddBytes(buf, wordLen, (Byte *)word);
1048 * If added characters to the buffer, need to add a space
1049 * before we add any more. If we didn't add any, just return
1050 * the previous value of addSpace.
1052 return ((Buf_Size(buf) != origSize) || addSpace);
1055 * Common code for anchored substitutions:
1056 * addSpace was set TRUE if characters were added to the buffer.
1062 Buf_AddByte(buf, (Byte)' ');
1064 Buf_AddBytes(buf, wordLen, (Byte *)word);
1069 *-----------------------------------------------------------------------
1071 * Print the error caused by a regcomp or regexec call.
1077 * An error gets printed.
1079 *-----------------------------------------------------------------------
1082 VarREError(err, pat, str)
1090 errlen = regerror(err, pat, 0, 0);
1091 errbuf = emalloc(errlen);
1092 regerror(err, pat, errbuf, errlen);
1093 Error("%s: %s", str, errbuf);
1099 *-----------------------------------------------------------------------
1100 * VarRESubstitute --
1101 * Perform a regex substitution on the given word, placing the
1102 * result in the passed buffer.
1105 * TRUE if a space is needed before more characters are added.
1110 *-----------------------------------------------------------------------
1113 VarRESubstitute(word, addSpace, buf, patternp)
1117 ClientData patternp;
1126 #define MAYBE_ADD_SPACE() \
1127 if (addSpace && !added) \
1128 Buf_AddByte(buf, ' '); \
1135 if ((pat->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) ==
1136 (VAR_SUB_ONE|VAR_SUB_MATCHED))
1140 xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
1145 pat->flags |= VAR_SUB_MATCHED;
1146 if (pat->matches[0].rm_so > 0) {
1148 Buf_AddBytes(buf, pat->matches[0].rm_so, wp);
1151 for (rp = pat->replace; *rp; rp++) {
1152 if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
1154 Buf_AddByte(buf,rp[1]);
1157 else if ((*rp == '&') ||
1158 ((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
1176 if (n > pat->nsub) {
1177 Error("No subexpression %s", &errstr[0]);
1180 } else if ((pat->matches[n].rm_so == -1) &&
1181 (pat->matches[n].rm_eo == -1)) {
1182 Error("No match for subexpression %s", &errstr[0]);
1186 subbuf = wp + pat->matches[n].rm_so;
1187 sublen = pat->matches[n].rm_eo - pat->matches[n].rm_so;
1192 Buf_AddBytes(buf, sublen, subbuf);
1196 Buf_AddByte(buf, *rp);
1199 wp += pat->matches[0].rm_eo;
1200 if (pat->flags & VAR_SUB_GLOBAL) {
1201 flags |= REG_NOTBOL;
1202 if (pat->matches[0].rm_so == 0 && pat->matches[0].rm_eo == 0) {
1204 Buf_AddByte(buf, *wp);
1213 Buf_AddBytes(buf, strlen(wp), wp);
1217 VarREError(xrv, &pat->re, "Unexpected regex error");
1222 Buf_AddBytes(buf,strlen(wp),wp);
1226 return(addSpace||added);
1231 *-----------------------------------------------------------------------
1233 * Modify each of the words of the passed string using the given
1234 * function. Used to implement all modifiers.
1237 * A string of all the words modified appropriately.
1242 *-----------------------------------------------------------------------
1245 VarModify (str, modProc, datum)
1246 char *str; /* String whose words should be trimmed */
1247 /* Function to use to modify them */
1248 Boolean (*modProc) __P((char *, Boolean, Buffer, ClientData));
1249 ClientData datum; /* Datum to pass it */
1251 Buffer buf; /* Buffer for the new string */
1252 Boolean addSpace; /* TRUE if need to add a space to the
1253 * buffer before adding the trimmed
1255 char **av; /* word list [first word does not count] */
1261 av = brk_string(str, &ac, FALSE);
1263 for (i = 1; i < ac; i++)
1264 addSpace = (*modProc)(av[i], addSpace, buf, datum);
1266 Buf_AddByte (buf, '\0');
1267 str = (char *)Buf_GetAll (buf, (int *)NULL);
1268 Buf_Destroy (buf, FALSE);
1273 *-----------------------------------------------------------------------
1275 * Pass through the tstr looking for 1) escaped delimiters,
1276 * '$'s and backslashes (place the escaped character in
1277 * uninterpreted) and 2) unescaped $'s that aren't before
1278 * the delimiter (expand the variable substitution unless flags
1279 * has VAR_NOSUBST set).
1280 * Return the expanded string or NULL if the delimiter was missing
1281 * If pattern is specified, handle escaped ampersands, and replace
1282 * unescaped ampersands with the lhs of the pattern.
1285 * A string of all the words modified appropriately.
1286 * If length is specified, return the string length of the buffer
1287 * If flags is specified and the last character of the pattern is a
1288 * $ set the VAR_MATCH_END bit of flags.
1292 *-----------------------------------------------------------------------
1295 VarGetPattern(ctxt, err, tstr, delim, flags, length, pattern)
1302 VarPattern *pattern;
1305 Buffer buf = Buf_Init(0);
1310 #define IS_A_MATCH(cp, delim) \
1311 ((cp[0] == '\\') && ((cp[1] == delim) || \
1312 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
1315 * Skim through until the matching delimiter is found;
1316 * pick up variable substitutions on the way. Also allow
1317 * backslashes to quote the delimiter, $, and \, but don't
1318 * touch other backslashes.
1320 for (cp = *tstr; *cp && (*cp != delim); cp++) {
1321 if (IS_A_MATCH(cp, delim)) {
1322 Buf_AddByte(buf, (Byte) cp[1]);
1324 } else if (*cp == '$') {
1325 if (cp[1] == delim) {
1327 Buf_AddByte(buf, (Byte) *cp);
1330 * Unescaped $ at end of pattern => anchor
1333 *flags |= VAR_MATCH_END;
1335 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
1341 * If unescaped dollar sign not before the
1342 * delimiter, assume it's a variable
1343 * substitution and recurse.
1345 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1346 Buf_AddBytes(buf, strlen(cp2), (Byte *) cp2);
1353 if (*cp2 == '(' || *cp2 == '{') {
1355 * Find the end of this variable reference
1356 * and suck it in without further ado.
1357 * It will be interperated later.
1360 int want = (*cp2 == '(') ? ')' : '}';
1363 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
1364 if (cp2[-1] != '\\') {
1371 Buf_AddBytes(buf, cp2 - cp, (Byte *)cp);
1374 Buf_AddByte(buf, (Byte) *cp);
1378 else if (pattern && *cp == '&')
1379 Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
1381 Buf_AddByte(buf, (Byte) *cp);
1384 Buf_AddByte(buf, (Byte) '\0');
1393 cp = (char *) Buf_GetAll(buf, length);
1394 *length -= 1; /* Don't count the NULL */
1395 Buf_Destroy(buf, FALSE);
1402 *-----------------------------------------------------------------------
1404 * Quote shell meta-characters in the string
1412 *-----------------------------------------------------------------------
1420 /* This should cover most shells :-( */
1421 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
1423 buf = Buf_Init (MAKE_BSIZE);
1424 for (; *str; str++) {
1425 if (strchr(meta, *str) != NULL)
1426 Buf_AddByte(buf, (Byte)'\\');
1427 Buf_AddByte(buf, (Byte)*str);
1429 Buf_AddByte(buf, (Byte) '\0');
1430 str = (char *)Buf_GetAll (buf, (int *)NULL);
1431 Buf_Destroy (buf, FALSE);
1436 *-----------------------------------------------------------------------
1438 * Given the start of a variable invocation, extract the variable
1439 * name and find its value, then modify it according to the
1443 * The (possibly-modified) value of the variable or var_Error if the
1444 * specification is invalid. The length of the specification is
1445 * placed in *lengthPtr (for invalid specifications, this is just
1447 * A Boolean in *freePtr telling whether the returned string should
1448 * be freed by the caller.
1453 *-----------------------------------------------------------------------
1456 Var_Parse (str, ctxt, err, lengthPtr, freePtr)
1457 char *str; /* The string to parse */
1458 GNode *ctxt; /* The context for the variable */
1459 Boolean err; /* TRUE if undefined variables are an error */
1460 int *lengthPtr; /* OUT: The length of the specification */
1461 Boolean *freePtr; /* OUT: TRUE if caller should free result */
1463 register char *tstr; /* Pointer into str */
1464 Var *v; /* Variable in invocation */
1465 char *cp; /* Secondary pointer into str (place marker
1467 Boolean haveModifier;/* TRUE if have modifiers for the variable */
1468 register char endc; /* Ending character when variable in parens
1470 register char startc=0; /* Starting character when variable in parens
1472 int cnt; /* Used to count brace pairs when variable in
1473 * in parens or braces */
1476 Boolean dynamic; /* TRUE if the variable is local and we're
1477 * expanding it in a non-local context. This
1478 * is done to support dynamic sources. The
1479 * result is just the invocation, unaltered */
1480 int vlen; /* length of variable name, after embedded variable
1487 if (str[1] != '(' && str[1] != '{') {
1489 * If it's not bounded by braces of some sort, life is much simpler.
1490 * We just need to check for the first character and return the
1491 * value if it exists.
1498 v = VarFind (name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1499 if (v == (Var *)NIL) {
1502 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
1504 * If substituting a local variable in a non-local context,
1505 * assume it's for dynamic source stuff. We have to handle
1506 * this specially and return the longhand for the variable
1507 * with the dollar sign escaped so it makes it back to the
1508 * caller. Only four of the local variables are treated
1509 * specially as they are the only four that will be set
1510 * when dynamic sources are expanded.
1512 /* XXX: It looks like $% and $! are reversed here */
1515 return("$(.TARGET)");
1517 return("$(.ARCHIVE)");
1519 return("$(.PREFIX)");
1521 return("$(.MEMBER)");
1527 return (err ? var_Error : varNoError);
1529 haveModifier = FALSE;
1534 /* build up expanded variable name in this buffer */
1535 Buffer buf = Buf_Init(MAKE_BSIZE);
1538 endc = startc == '(' ? ')' : '}';
1541 * Skip to the end character or a colon, whichever comes first,
1542 * replacing embedded variables as we go.
1544 for (tstr = str + 2; *tstr != '\0' && *tstr != endc && *tstr != ':'; tstr++)
1548 char* rval = Var_Parse(tstr, ctxt, err, &rlen, &rfree);
1550 if (rval == var_Error) {
1551 Fatal("Error expanding embedded variable.");
1552 } else if (rval != NULL) {
1553 Buf_AddBytes(buf, strlen(rval), (Byte *) rval);
1559 Buf_AddByte(buf, (Byte) *tstr);
1561 if (*tstr == '\0') {
1563 * If we never did find the end character, return NULL
1564 * right now, setting the length to be the distance to
1565 * the end of the string, since that's what make does.
1567 *lengthPtr = tstr - str;
1571 haveModifier = (*tstr == ':');
1574 Buf_AddByte(buf, (Byte) '\0');
1575 str = Buf_GetAll(buf, NULL);
1578 v = VarFind (str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1579 if ((v == (Var *)NIL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
1580 (vlen == 2) && (str[1] == 'F' || str[1] == 'D'))
1583 * Check for bogus D and F forms of local variables since we're
1584 * in a local context and the name is the right length.
1598 * Well, it's local -- go look for it.
1602 v = VarFind(vname, ctxt, 0);
1604 if (v != (Var *)NIL && !haveModifier) {
1606 * No need for nested expansion or anything, as we're
1607 * the only one who sets these things and we sure don't
1608 * put nested invocations in them...
1610 val = (char *)Buf_GetAll(v->val, (int *)NULL);
1612 if (str[1] == 'D') {
1613 val = VarModify(val, VarHead, (ClientData)0);
1615 val = VarModify(val, VarTail, (ClientData)0);
1618 * Resulting string is dynamically allocated, so
1619 * tell caller to free it.
1622 *lengthPtr = tstr-start+1;
1624 Buf_Destroy(buf, TRUE);
1632 if (v == (Var *)NIL) {
1634 (((vlen == 2) && (str[1] == 'F' ||
1635 str[1] == 'D')))) &&
1636 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1639 * If substituting a local variable in a non-local context,
1640 * assume it's for dynamic source stuff. We have to handle
1641 * this specially and return the longhand for the variable
1642 * with the dollar sign escaped so it makes it back to the
1643 * caller. Only four of the local variables are treated
1644 * specially as they are the only four that will be set
1645 * when dynamic sources are expanded.
1655 } else if ((vlen > 2) && (str[0] == '.') &&
1656 isupper((unsigned char) str[1]) &&
1657 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1662 if ((strncmp(str, ".TARGET", len) == 0) ||
1663 (strncmp(str, ".ARCHIVE", len) == 0) ||
1664 (strncmp(str, ".PREFIX", len) == 0) ||
1665 (strncmp(str, ".MEMBER", len) == 0))
1671 if (!haveModifier) {
1673 * No modifiers -- have specification length so we can return
1676 *lengthPtr = tstr - start + 1;
1679 str = emalloc(*lengthPtr + 1);
1680 strncpy(str, start, *lengthPtr);
1681 str[*lengthPtr] = '\0';
1683 Buf_Destroy(buf, TRUE);
1686 Buf_Destroy(buf, TRUE);
1687 return (err ? var_Error : varNoError);
1691 * Still need to get to the end of the variable specification,
1692 * so kludge up a Var structure for the modifications
1694 v = (Var *) emalloc(sizeof(Var));
1696 v->val = Buf_Init(1);
1697 v->flags = VAR_JUNK;
1700 Buf_Destroy(buf, TRUE);
1703 if (v->flags & VAR_IN_USE) {
1704 Fatal("Variable %s is recursive.", v->name);
1707 v->flags |= VAR_IN_USE;
1710 * Before doing any modification, we have to make sure the value
1711 * has been fully expanded. If it looks like recursion might be
1712 * necessary (there's a dollar sign somewhere in the variable's value)
1713 * we just call Var_Subst to do any other substitutions that are
1714 * necessary. Note that the value returned by Var_Subst will have
1715 * been dynamically-allocated, so it will need freeing when we
1718 str = (char *)Buf_GetAll(v->val, (int *)NULL);
1719 if (strchr (str, '$') != (char *)NULL) {
1720 str = Var_Subst(NULL, str, ctxt, err);
1724 v->flags &= ~VAR_IN_USE;
1727 * Now we need to apply any modifiers the user wants applied.
1729 * :M<pattern> words which match the given <pattern>.
1730 * <pattern> is of the standard file
1732 * :S<d><pat1><d><pat2><d>[g]
1733 * Substitute <pat2> for <pat1> in the value
1734 * :C<d><pat1><d><pat2><d>[g]
1735 * Substitute <pat2> for regex <pat1> in the value
1736 * :H Substitute the head of each word
1737 * :T Substitute the tail of each word
1738 * :E Substitute the extension (minus '.') of
1740 * :R Substitute the root of each word
1741 * (pathname minus the suffix).
1742 * :lhs=rhs Like :S, but the rhs goes to the end of
1744 * :U Converts variable to upper-case.
1745 * :L Converts variable to lower-case.
1747 if ((str != (char *)NULL) && haveModifier) {
1749 * Skip initial colon while putting it back.
1752 while (*tstr != endc) {
1753 char *newStr; /* New value to return */
1754 char termc; /* Character which terminated scan */
1757 printf("Applying :%c to \"%s\"\n", *tstr, str);
1761 if (tstr[1] == endc || tstr[1] == ':') {
1763 buf = Buf_Init(MAKE_BSIZE);
1764 for (cp = str; *cp ; cp++)
1765 Buf_AddByte(buf, (Byte) toupper(*cp));
1767 Buf_AddByte(buf, (Byte) '\0');
1768 newStr = (char *) Buf_GetAll(buf, (int *) NULL);
1769 Buf_Destroy(buf, FALSE);
1777 if (tstr[1] == endc || tstr[1] == ':') {
1779 buf = Buf_Init(MAKE_BSIZE);
1780 for (cp = str; *cp ; cp++)
1781 Buf_AddByte(buf, (Byte) tolower(*cp));
1783 Buf_AddByte(buf, (Byte) '\0');
1784 newStr = (char *) Buf_GetAll(buf, (int *) NULL);
1785 Buf_Destroy(buf, FALSE);
1801 *cp != '\0' && *cp != ':' && *cp != endc;
1804 if (*cp == '\\' && (cp[1] == ':' || cp[1] == endc)){
1813 * Need to compress the \:'s out of the pattern, so
1814 * allocate enough room to hold the uncompressed
1815 * pattern (note that cp started at tstr+1, so
1816 * cp - tstr takes the null byte into account) and
1817 * compress the pattern into the space.
1819 pattern = emalloc(cp - tstr);
1820 for (cp2 = pattern, cp = tstr + 1;
1824 if ((*cp == '\\') &&
1825 (cp[1] == ':' || cp[1] == endc)) {
1834 if (*tstr == 'M' || *tstr == 'm') {
1835 newStr = VarModify(str, VarMatch, (ClientData)pattern);
1837 newStr = VarModify(str, VarNoMatch,
1838 (ClientData)pattern);
1848 register char delim;
1849 Buffer buf; /* Buffer for patterns */
1856 * If pattern begins with '^', it is anchored to the
1857 * start of the word -- skip over it and flag pattern.
1860 pattern.flags |= VAR_MATCH_START;
1867 * Pass through the lhs looking for 1) escaped delimiters,
1868 * '$'s and backslashes (place the escaped character in
1869 * uninterpreted) and 2) unescaped $'s that aren't before
1870 * the delimiter (expand the variable substitution).
1871 * The result is left in the Buffer buf.
1873 for (cp = tstr; *cp != '\0' && *cp != delim; cp++) {
1874 if ((*cp == '\\') &&
1875 ((cp[1] == delim) ||
1879 Buf_AddByte(buf, (Byte)cp[1]);
1881 } else if (*cp == '$') {
1882 if (cp[1] != delim) {
1884 * If unescaped dollar sign not before the
1885 * delimiter, assume it's a variable
1886 * substitution and recurse.
1892 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1893 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
1900 * Unescaped $ at end of pattern => anchor
1903 pattern.flags |= VAR_MATCH_END;
1906 Buf_AddByte(buf, (Byte)*cp);
1910 Buf_AddByte(buf, (Byte)'\0');
1913 * If lhs didn't end with the delimiter, complain and
1917 *lengthPtr = cp - start + 1;
1921 Buf_Destroy(buf, TRUE);
1922 Error("Unclosed substitution for %s (%c missing)",
1928 * Fetch pattern and destroy buffer, but preserve the data
1929 * in it, since that's our lhs. Note that Buf_GetAll
1930 * will return the actual number of bytes, which includes
1931 * the null byte, so we have to decrement the length by
1934 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1936 Buf_Destroy(buf, FALSE);
1939 * Now comes the replacement string. Three things need to
1940 * be done here: 1) need to compress escaped delimiters and
1941 * ampersands and 2) need to replace unescaped ampersands
1942 * with the l.h.s. (since this isn't regexp, we can do
1943 * it right here) and 3) expand any variable substitutions.
1948 for (cp = tstr; *cp != '\0' && *cp != delim; cp++) {
1949 if ((*cp == '\\') &&
1950 ((cp[1] == delim) ||
1955 Buf_AddByte(buf, (Byte)cp[1]);
1957 } else if ((*cp == '$') && (cp[1] != delim)) {
1962 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1963 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
1968 } else if (*cp == '&') {
1969 Buf_AddBytes(buf, pattern.leftLen,
1970 (Byte *)pattern.lhs);
1972 Buf_AddByte(buf, (Byte)*cp);
1976 Buf_AddByte(buf, (Byte)'\0');
1979 * If didn't end in delimiter character, complain
1982 *lengthPtr = cp - start + 1;
1986 Buf_Destroy(buf, TRUE);
1987 Error("Unclosed substitution for %s (%c missing)",
1992 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1994 Buf_Destroy(buf, FALSE);
1997 * Check for global substitution. If 'g' after the final
1998 * delimiter, substitution is global and is marked that
2003 pattern.flags |= VAR_SUB_GLOBAL;
2008 newStr = VarModify(str, VarSubstitute,
2009 (ClientData)&pattern);
2011 * Free the two strings.
2019 VarREPattern pattern;
2029 if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
2030 NULL, NULL)) == NULL) {
2031 /* was: goto cleanup */
2032 *lengthPtr = cp - start + 1;
2036 Error("Unclosed substitution for %s (%c missing)",
2041 if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
2042 delim, NULL, NULL, NULL)) == NULL){
2045 /* was: goto cleanup */
2046 *lengthPtr = cp - start + 1;
2050 Error("Unclosed substitution for %s (%c missing)",
2058 pattern.flags |= VAR_SUB_GLOBAL;
2061 pattern.flags |= VAR_SUB_ONE;
2069 error = regcomp(&pattern.re, re, REG_EXTENDED);
2072 *lengthPtr = cp - start + 1;
2073 VarREError(error, &pattern.re, "RE substitution error");
2074 free(pattern.replace);
2078 pattern.nsub = pattern.re.re_nsub + 1;
2079 if (pattern.nsub < 1)
2081 if (pattern.nsub > 10)
2083 pattern.matches = emalloc(pattern.nsub *
2084 sizeof(regmatch_t));
2085 newStr = VarModify(str, VarRESubstitute,
2086 (ClientData) &pattern);
2087 regfree(&pattern.re);
2088 free(pattern.replace);
2089 free(pattern.matches);
2093 if (tstr[1] == endc || tstr[1] == ':') {
2094 newStr = VarQuote (str);
2101 if (tstr[1] == endc || tstr[1] == ':') {
2102 newStr = VarModify (str, VarTail, (ClientData)0);
2109 if (tstr[1] == endc || tstr[1] == ':') {
2110 newStr = VarModify (str, VarHead, (ClientData)0);
2117 if (tstr[1] == endc || tstr[1] == ':') {
2118 newStr = VarModify (str, VarSuffix, (ClientData)0);
2125 if (tstr[1] == endc || tstr[1] == ':') {
2126 newStr = VarModify (str, VarRoot, (ClientData)0);
2134 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
2136 newStr = Cmd_Exec (str, &err);
2149 * This can either be a bogus modifier or a System-V
2150 * substitution command.
2158 * First we make a pass through the string trying
2159 * to verify it is a SYSV-make-style translation:
2160 * it must be: <string1>=<string2>)
2164 while (*cp != '\0' && cnt) {
2167 /* continue looking for endc */
2169 else if (*cp == endc)
2171 else if (*cp == startc)
2176 if (*cp == endc && eqFound) {
2179 * Now we break this sucker into the lhs and
2180 * rhs. We must null terminate them of course.
2182 for (cp = tstr; *cp != '='; cp++)
2185 pattern.leftLen = cp - tstr;
2193 else if (*cp == startc)
2198 pattern.rightLen = cp - pattern.rhs;
2202 * SYSV modifications happen through the whole
2203 * string. Note the pattern is anchored at the end.
2205 newStr = VarModify(str, VarSYSVMatch,
2206 (ClientData)&pattern);
2209 * Restore the nulled characters
2211 pattern.lhs[pattern.leftLen] = '=';
2212 pattern.rhs[pattern.rightLen] = endc;
2217 Error ("Unknown modifier '%c'\n", *tstr);
2219 *cp != ':' && *cp != endc && *cp != '\0';
2228 printf("Result is \"%s\"\n", newStr);
2235 if (str != var_Error) {
2240 if (termc == '\0') {
2241 Error("Unclosed variable specification for %s", v->name);
2242 } else if (termc == ':') {
2249 *lengthPtr = tstr - start + 1;
2251 *lengthPtr = tstr - start + 1;
2255 if (v->flags & VAR_FROM_ENV) {
2256 Boolean destroy = FALSE;
2258 if (str != (char *)Buf_GetAll(v->val, (int *)NULL)) {
2262 * Returning the value unmodified, so tell the caller to free
2267 Buf_Destroy(v->val, destroy);
2269 } else if (v->flags & VAR_JUNK) {
2271 * Perform any free'ing needed and set *freePtr to FALSE so the caller
2272 * doesn't try to free a static pointer.
2278 Buf_Destroy(v->val, TRUE);
2281 str = emalloc(*lengthPtr + 1);
2282 strncpy(str, start, *lengthPtr);
2283 str[*lengthPtr] = '\0';
2286 str = err ? var_Error : varNoError;
2293 *-----------------------------------------------------------------------
2295 * Substitute for all variables in the given string in the given context
2296 * If undefErr is TRUE, Parse_Error will be called when an undefined
2297 * variable is encountered.
2300 * The resulting string.
2303 * None. The old string must be freed by the caller
2304 *-----------------------------------------------------------------------
2307 Var_Subst (var, str, ctxt, undefErr)
2308 char *var; /* Named variable || NULL for all */
2309 char *str; /* the string in which to substitute */
2310 GNode *ctxt; /* the context wherein to find variables */
2311 Boolean undefErr; /* TRUE if undefineds are an error */
2313 Buffer buf; /* Buffer for forming things */
2314 char *val; /* Value to substitute for a variable */
2315 int length; /* Length of the variable invocation */
2316 Boolean doFree; /* Set true if val should be freed */
2317 static Boolean errorReported; /* Set true if an error has already
2318 * been reported to prevent a plethora
2319 * of messages when recursing */
2321 buf = Buf_Init (MAKE_BSIZE);
2322 errorReported = FALSE;
2325 if (var == NULL && (*str == '$') && (str[1] == '$')) {
2327 * A dollar sign may be escaped either with another dollar sign.
2328 * In such a case, we skip over the escape character and store the
2329 * dollar sign into the buffer directly.
2332 Buf_AddByte(buf, (Byte)*str);
2334 } else if (*str != '$') {
2336 * Skip as many characters as possible -- either to the end of
2337 * the string or to the next dollar sign (variable invocation).
2341 for (cp = str++; *str != '$' && *str != '\0'; str++)
2343 Buf_AddBytes(buf, str - cp, (Byte *)cp);
2348 if (str[1] != '(' && str[1] != '{') {
2349 if (str[1] != *var) {
2350 Buf_AddBytes(buf, 2, (Byte *) str);
2362 * Scan up to the end of the variable name.
2364 for (p = &str[2]; *p &&
2365 *p != ':' && *p != ')' && *p != '}'; p++)
2369 * A variable inside the variable. We cannot expand
2370 * the external variable yet, so we try again with
2374 Buf_AddBytes(buf, p - str, (Byte *) str);
2379 if (strncmp(var, str + 2, p - str - 2) != 0 ||
2380 var[p - str - 2] != '\0') {
2382 * Not the variable we want to expand, scan
2383 * until the next variable
2385 for (;*p != '$' && *p != '\0'; p++)
2387 Buf_AddBytes(buf, p - str, (Byte *) str);
2400 val = Var_Parse (str, ctxt, undefErr, &length, &doFree);
2403 * When we come down here, val should either point to the
2404 * value of this variable, suitably modified, or be NULL.
2405 * Length should be the total length of the potential
2406 * variable invocation (from $ to end character...)
2408 if (val == var_Error || val == varNoError) {
2410 * If performing old-time variable substitution, skip over
2411 * the variable and continue with the substitution. Otherwise,
2412 * store the dollar sign and advance str so we continue with
2417 } else if (undefErr) {
2419 * If variable is undefined, complain and skip the
2420 * variable. The complaint will stop us from doing anything
2421 * when the file is parsed.
2423 if (!errorReported) {
2424 Parse_Error (PARSE_FATAL,
2425 "Undefined variable \"%.*s\"",length,str);
2428 errorReported = TRUE;
2430 Buf_AddByte (buf, (Byte)*str);
2435 * We've now got a variable structure to store in. But first,
2436 * advance the string pointer.
2441 * Copy all the characters from the variable value straight
2442 * into the new string.
2444 Buf_AddBytes (buf, strlen (val), (Byte *)val);
2446 free ((Address)val);
2452 Buf_AddByte (buf, '\0');
2453 str = (char *)Buf_GetAll (buf, (int *)NULL);
2454 Buf_Destroy (buf, FALSE);
2459 *-----------------------------------------------------------------------
2461 * Return the tail from each of a list of words. Used to set the
2462 * System V local variables.
2465 * The resulting string.
2470 *-----------------------------------------------------------------------
2474 char *file; /* Filename to modify */
2476 return(VarModify(file, VarTail, (ClientData)0));
2480 *-----------------------------------------------------------------------
2482 * Find the leading components of a (list of) filename(s).
2483 * XXX: VarHead does not replace foo by ., as (sun) System V make
2487 * The leading components.
2492 *-----------------------------------------------------------------------
2496 char *file; /* Filename to manipulate */
2498 return(VarModify(file, VarHead, (ClientData)0));
2502 *-----------------------------------------------------------------------
2504 * Initialize the module
2510 * The VAR_CMD and VAR_GLOBAL contexts are created
2511 *-----------------------------------------------------------------------
2516 VAR_GLOBAL = Targ_NewGN ("Global");
2517 VAR_CMD = Targ_NewGN ("Command");
2518 allVars = Lst_Init(FALSE);
2526 Lst_Destroy(allVars, VarDelete);
2530 /****************** PRINT DEBUGGING INFO *****************/
2532 VarPrintVar (vp, dummy)
2536 Var *v = (Var *) vp;
2537 printf ("%-16s = %s\n", v->name, (char *) Buf_GetAll(v->val, (int *)NULL));
2538 return (dummy ? 0 : 0);
2542 *-----------------------------------------------------------------------
2544 * print all variables in a context
2545 *-----------------------------------------------------------------------
2551 Lst_ForEach (ctxt->context, VarPrintVar, (ClientData) 0);