Home | History | Annotate | Line # | Download | only in make
var.c revision 1.62
      1 /*	$NetBSD: var.c,v 1.62 2001/06/09 05:22:47 sjg Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1988, 1989, 1990, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  * Copyright (c) 1989 by Berkeley Softworks
      7  * All rights reserved.
      8  *
      9  * This code is derived from software contributed to Berkeley by
     10  * Adam de Boor.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. All advertising materials mentioning features or use of this software
     21  *    must display the following acknowledgement:
     22  *	This product includes software developed by the University of
     23  *	California, Berkeley and its contributors.
     24  * 4. Neither the name of the University nor the names of its contributors
     25  *    may be used to endorse or promote products derived from this software
     26  *    without specific prior written permission.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     38  * SUCH DAMAGE.
     39  */
     40 
     41 #ifdef MAKE_BOOTSTRAP
     42 static char rcsid[] = "$NetBSD: var.c,v 1.62 2001/06/09 05:22:47 sjg Exp $";
     43 #else
     44 #include <sys/cdefs.h>
     45 #ifndef lint
     46 #if 0
     47 static char sccsid[] = "@(#)var.c	8.3 (Berkeley) 3/19/94";
     48 #else
     49 __RCSID("$NetBSD: var.c,v 1.62 2001/06/09 05:22:47 sjg Exp $");
     50 #endif
     51 #endif /* not lint */
     52 #endif
     53 
     54 /*-
     55  * var.c --
     56  *	Variable-handling functions
     57  *
     58  * Interface:
     59  *	Var_Set	  	    Set the value of a variable in the given
     60  *	    	  	    context. The variable is created if it doesn't
     61  *	    	  	    yet exist. The value and variable name need not
     62  *	    	  	    be preserved.
     63  *
     64  *	Var_Append	    Append more characters to an existing variable
     65  *	    	  	    in the given context. The variable needn't
     66  *	    	  	    exist already -- it will be created if it doesn't.
     67  *	    	  	    A space is placed between the old value and the
     68  *	    	  	    new one.
     69  *
     70  *	Var_Exists	    See if a variable exists.
     71  *
     72  *	Var_Value 	    Return the value of a variable in a context or
     73  *	    	  	    NULL if the variable is undefined.
     74  *
     75  *	Var_Subst 	    Substitute named variable, or all variables if
     76  *			    NULL in a string using
     77  *	    	  	    the given context as the top-most one. If the
     78  *	    	  	    third argument is non-zero, Parse_Error is
     79  *	    	  	    called if any variables are undefined.
     80  *
     81  *	Var_Parse 	    Parse a variable expansion from a string and
     82  *	    	  	    return the result and the number of characters
     83  *	    	  	    consumed.
     84  *
     85  *	Var_Delete	    Delete a variable in a context.
     86  *
     87  *	Var_Init  	    Initialize this module.
     88  *
     89  * Debugging:
     90  *	Var_Dump  	    Print out all variables defined in the given
     91  *	    	  	    context.
     92  *
     93  * XXX: There's a lot of duplication in these functions.
     94  */
     95 
     96 #include    <ctype.h>
     97 #ifndef NO_REGEX
     98 #include    <sys/types.h>
     99 #include    <regex.h>
    100 #endif
    101 #include    <stdlib.h>
    102 #include    "make.h"
    103 #include    "buf.h"
    104 
    105 /*
    106  * This is a harmless return value for Var_Parse that can be used by Var_Subst
    107  * to determine if there was an error in parsing -- easier than returning
    108  * a flag, as things outside this module don't give a hoot.
    109  */
    110 char 	var_Error[] = "";
    111 
    112 /*
    113  * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
    114  * set false. Why not just use a constant? Well, gcc likes to condense
    115  * identical string instances...
    116  */
    117 static char	varNoError[] = "";
    118 
    119 /*
    120  * Internally, variables are contained in four different contexts.
    121  *	1) the environment. They may not be changed. If an environment
    122  *	    variable is appended-to, the result is placed in the global
    123  *	    context.
    124  *	2) the global context. Variables set in the Makefile are located in
    125  *	    the global context. It is the penultimate context searched when
    126  *	    substituting.
    127  *	3) the command-line context. All variables set on the command line
    128  *	   are placed in this context. They are UNALTERABLE once placed here.
    129  *	4) the local context. Each target has associated with it a context
    130  *	   list. On this list are located the structures describing such
    131  *	   local variables as $(@) and $(*)
    132  * The four contexts are searched in the reverse order from which they are
    133  * listed.
    134  */
    135 GNode          *VAR_GLOBAL;   /* variables from the makefile */
    136 GNode          *VAR_CMD;      /* variables defined on the command-line */
    137 
    138 #define FIND_CMD	0x1   /* look in VAR_CMD when searching */
    139 #define FIND_GLOBAL	0x2   /* look in VAR_GLOBAL as well */
    140 #define FIND_ENV  	0x4   /* look in the environment also */
    141 
    142 typedef struct Var {
    143     char          *name;	/* the variable's name */
    144     Buffer	  val;	    	/* its value */
    145     int	    	  flags;    	/* miscellaneous status flags */
    146 #define VAR_IN_USE	1   	    /* Variable's value currently being used.
    147 				     * Used to avoid recursion */
    148 #define VAR_FROM_ENV	2   	    /* Variable comes from the environment */
    149 #define VAR_JUNK  	4   	    /* Variable is a junk variable that
    150 				     * should be destroyed when done with
    151 				     * it. Used by Var_Parse for undefined,
    152 				     * modified variables */
    153 #define VAR_KEEP	8	    /* Variable is VAR_JUNK, but we found
    154 				     * a use for it in some modifier and
    155 				     * the value is therefore valid */
    156 }  Var;
    157 
    158 
    159 /* Var*Pattern flags */
    160 #define VAR_SUB_GLOBAL	0x01	/* Apply substitution globally */
    161 #define VAR_SUB_ONE	0x02	/* Apply substitution to one word */
    162 #define VAR_SUB_MATCHED	0x04	/* There was a match */
    163 #define VAR_MATCH_START	0x08	/* Match at start of word */
    164 #define VAR_MATCH_END	0x10	/* Match at end of word */
    165 #define VAR_NOSUBST	0x20	/* don't expand vars in VarGetPattern */
    166 
    167 typedef struct {
    168     char    	  *lhs;	    /* String to match */
    169     int	    	   leftLen; /* Length of string */
    170     char    	  *rhs;	    /* Replacement string (w/ &'s removed) */
    171     int	    	  rightLen; /* Length of replacement */
    172     int	    	  flags;
    173 } VarPattern;
    174 
    175 typedef struct {
    176     GNode	*ctxt;		/* variable context */
    177     char	*tvar;		/* name of temp var */
    178     int		tvarLen;
    179     char	*str;		/* string to expand */
    180     int		strLen;
    181     int		err;		/* err for not defined */
    182 } VarLoop_t;
    183 
    184 #ifndef NO_REGEX
    185 typedef struct {
    186     regex_t	   re;
    187     int		   nsub;
    188     regmatch_t 	  *matches;
    189     char 	  *replace;
    190     int		   flags;
    191 } VarREPattern;
    192 #endif
    193 
    194 static Var *VarFind __P((char *, GNode *, int));
    195 static void VarAdd __P((char *, char *, GNode *));
    196 static Boolean VarHead __P((GNode *, char *, Boolean, Buffer, ClientData));
    197 static Boolean VarTail __P((GNode *, char *, Boolean, Buffer, ClientData));
    198 static Boolean VarSuffix __P((GNode *, char *, Boolean, Buffer, ClientData));
    199 static Boolean VarRoot __P((GNode *, char *, Boolean, Buffer, ClientData));
    200 static Boolean VarMatch __P((GNode *, char *, Boolean, Buffer, ClientData));
    201 #ifdef SYSVVARSUB
    202 static Boolean VarSYSVMatch __P((GNode *, char *, Boolean, Buffer,
    203 				 ClientData));
    204 #endif
    205 static Boolean VarNoMatch __P((GNode *, char *, Boolean, Buffer, ClientData));
    206 #ifndef NO_REGEX
    207 static void VarREError __P((int, regex_t *, const char *));
    208 static Boolean VarRESubstitute __P((GNode *, char *, Boolean, Buffer,
    209 				    ClientData));
    210 #endif
    211 static Boolean VarSubstitute __P((GNode *, char *, Boolean, Buffer,
    212 				  ClientData));
    213 static Boolean VarLoopExpand __P((GNode *, char *, Boolean, Buffer,
    214 				  ClientData));
    215 static char *VarGetPattern __P((GNode *, int, char **, int, int *, int *,
    216 				VarPattern *));
    217 static char *VarQuote __P((char *));
    218 static char *VarModify __P((GNode *, char *, Boolean (*)(GNode *, char *,
    219 							 Boolean, Buffer,
    220 							 ClientData),
    221 			    ClientData));
    222 static char *VarSort __P((char *));
    223 static char *VarUniq __P((char *));
    224 static int VarWordCompare __P((const void *, const void *));
    225 static void VarPrintVar __P((ClientData));
    226 
    227 /*-
    228  *-----------------------------------------------------------------------
    229  * VarFind --
    230  *	Find the given variable in the given context and any other contexts
    231  *	indicated.
    232  *
    233  * Results:
    234  *	A pointer to the structure describing the desired variable or
    235  *	NIL if the variable does not exist.
    236  *
    237  * Side Effects:
    238  *	None
    239  *-----------------------------------------------------------------------
    240  */
    241 static Var *
    242 VarFind (name, ctxt, flags)
    243     char           	*name;	/* name to find */
    244     GNode          	*ctxt;	/* context in which to find it */
    245     int             	flags;	/* FIND_GLOBAL set means to look in the
    246 				 * VAR_GLOBAL context as well.
    247 				 * FIND_CMD set means to look in the VAR_CMD
    248 				 * context also.
    249 				 * FIND_ENV set means to look in the
    250 				 * environment */
    251 {
    252     Hash_Entry         	*var;
    253     Var		  	*v;
    254 
    255 	/*
    256 	 * If the variable name begins with a '.', it could very well be one of
    257 	 * the local ones.  We check the name against all the local variables
    258 	 * and substitute the short version in for 'name' if it matches one of
    259 	 * them.
    260 	 */
    261 	if (*name == '.' && isupper((unsigned char) name[1]))
    262 		switch (name[1]) {
    263 		case 'A':
    264 			if (!strcmp(name, ".ALLSRC"))
    265 				name = ALLSRC;
    266 			if (!strcmp(name, ".ARCHIVE"))
    267 				name = ARCHIVE;
    268 			break;
    269 		case 'I':
    270 			if (!strcmp(name, ".IMPSRC"))
    271 				name = IMPSRC;
    272 			break;
    273 		case 'M':
    274 			if (!strcmp(name, ".MEMBER"))
    275 				name = MEMBER;
    276 			break;
    277 		case 'O':
    278 			if (!strcmp(name, ".OODATE"))
    279 				name = OODATE;
    280 			break;
    281 		case 'P':
    282 			if (!strcmp(name, ".PREFIX"))
    283 				name = PREFIX;
    284 			break;
    285 		case 'T':
    286 			if (!strcmp(name, ".TARGET"))
    287 				name = TARGET;
    288 			break;
    289 		}
    290     /*
    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'
    294      */
    295     var = Hash_FindEntry (&ctxt->context, name);
    296 
    297     if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
    298 	var = Hash_FindEntry (&VAR_CMD->context, name);
    299     }
    300     if (!checkEnvFirst && (var == NULL) && (flags & FIND_GLOBAL) &&
    301 	(ctxt != VAR_GLOBAL))
    302     {
    303 	var = Hash_FindEntry (&VAR_GLOBAL->context, name);
    304     }
    305     if ((var == NULL) && (flags & FIND_ENV)) {
    306 	char *env;
    307 
    308 	if ((env = getenv (name)) != NULL) {
    309 	    int	  	len;
    310 
    311 	    v = (Var *) emalloc(sizeof(Var));
    312 	    v->name = estrdup(name);
    313 
    314 	    len = strlen(env);
    315 
    316 	    v->val = Buf_Init(len);
    317 	    Buf_AddBytes(v->val, len, (Byte *)env);
    318 
    319 	    v->flags = VAR_FROM_ENV;
    320 	    return (v);
    321 	} else if (checkEnvFirst && (flags & FIND_GLOBAL) &&
    322 		   (ctxt != VAR_GLOBAL))
    323 	{
    324 	    var = Hash_FindEntry (&VAR_GLOBAL->context, name);
    325 	    if (var == NULL) {
    326 		return ((Var *) NIL);
    327 	    } else {
    328 		return ((Var *)Hash_GetValue(var));
    329 	    }
    330 	} else {
    331 	    return((Var *)NIL);
    332 	}
    333     } else if (var == NULL) {
    334 	return ((Var *) NIL);
    335     } else {
    336 	return ((Var *) Hash_GetValue(var));
    337     }
    338 }
    339 
    340 /*-
    341  *-----------------------------------------------------------------------
    342  * VarAdd  --
    343  *	Add a new variable of name name and value val to the given context
    344  *
    345  * Results:
    346  *	None
    347  *
    348  * Side Effects:
    349  *	The new variable is placed at the front of the given context
    350  *	The name and val arguments are duplicated so they may
    351  *	safely be freed.
    352  *-----------------------------------------------------------------------
    353  */
    354 static void
    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 */
    359 {
    360     register Var   *v;
    361     int	    	  len;
    362     Hash_Entry      *h;
    363 
    364     v = (Var *) emalloc (sizeof (Var));
    365 
    366     len = val ? strlen(val) : 0;
    367     v->val = Buf_Init(len+1);
    368     Buf_AddBytes(v->val, len, (Byte *)val);
    369 
    370     v->flags = 0;
    371 
    372     h = Hash_CreateEntry (&ctxt->context, name, NULL);
    373     Hash_SetValue(h, v);
    374     v->name = h->name;
    375     if (DEBUG(VAR)) {
    376 	printf("%s:%s = %s\n", ctxt->name, name, val);
    377     }
    378 }
    379 
    380 /*-
    381  *-----------------------------------------------------------------------
    382  * Var_Delete --
    383  *	Remove a variable from a context.
    384  *
    385  * Results:
    386  *	None.
    387  *
    388  * Side Effects:
    389  *	The Var structure is removed and freed.
    390  *
    391  *-----------------------------------------------------------------------
    392  */
    393 void
    394 Var_Delete(name, ctxt)
    395     char    	  *name;
    396     GNode	  *ctxt;
    397 {
    398     Hash_Entry 	  *ln;
    399 
    400     if (DEBUG(VAR)) {
    401 	printf("%s:delete %s\n", ctxt->name, name);
    402     }
    403     ln = Hash_FindEntry(&ctxt->context, name);
    404     if (ln != NULL) {
    405 	register Var 	  *v;
    406 
    407 	v = (Var *)Hash_GetValue(ln);
    408 	if (v->name != ln->name)
    409 		free(v->name);
    410 	Hash_DeleteEntry(&ctxt->context, ln);
    411 	Buf_Destroy(v->val, TRUE);
    412 	free((Address) v);
    413     }
    414 }
    415 
    416 /*-
    417  *-----------------------------------------------------------------------
    418  * Var_Set --
    419  *	Set the variable name to the value val in the given context.
    420  *
    421  * Results:
    422  *	None.
    423  *
    424  * Side Effects:
    425  *	If the variable doesn't yet exist, a new record is created for it.
    426  *	Else the old value is freed and the new one stuck in its place
    427  *
    428  * Notes:
    429  *	The variable is searched for only in its context before being
    430  *	created in that context. I.e. if the context is VAR_GLOBAL,
    431  *	only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
    432  *	VAR_CMD->context is searched. This is done to avoid the literally
    433  *	thousands of unnecessary strcmp's that used to be done to
    434  *	set, say, $(@) or $(<).
    435  *-----------------------------------------------------------------------
    436  */
    437 void
    438 Var_Set (name, val, ctxt)
    439     char           *name;	/* name of variable to set */
    440     char           *val;	/* value to give to the variable */
    441     GNode          *ctxt;	/* context in which to set it */
    442 {
    443     register Var   *v;
    444     char *cp = name;
    445 
    446     /*
    447      * We only look for a variable in the given context since anything set
    448      * here will override anything in a lower context, so there's not much
    449      * point in searching them all just to save a bit of memory...
    450      */
    451     if ((name = strchr(cp, '$'))) {
    452 	name = Var_Subst(NULL, cp, ctxt, 0);
    453     } else
    454 	name = cp;
    455     v = VarFind (name, ctxt, 0);
    456     if (v == (Var *) NIL) {
    457 	VarAdd (name, val, ctxt);
    458     } else {
    459 	Buf_Discard(v->val, Buf_Size(v->val));
    460 	Buf_AddBytes(v->val, strlen(val), (Byte *)val);
    461 
    462 	if (DEBUG(VAR)) {
    463 	    printf("%s:%s = %s\n", ctxt->name, name, val);
    464 	}
    465     }
    466     /*
    467      * Any variables given on the command line are automatically exported
    468      * to the environment (as per POSIX standard)
    469      */
    470     if (ctxt == VAR_CMD) {
    471 	char tmp[256];
    472 	char *exp;
    473 	int nbytes;
    474 
    475 	setenv(name, val, 1);
    476 
    477 	exp = 0;
    478 	if ((nbytes = snprintf(tmp, sizeof(tmp), "%s='%s'", name, val))
    479 	    < sizeof(tmp)) {
    480 	    exp = tmp;
    481 	} else {
    482 	    /* alloca is handy, but not everyone has it. */
    483 	    if ((exp = malloc(nbytes + 1)))
    484 		snprintf(exp, nbytes + 1, "%s='%s'", name, val);
    485 	}
    486 	if (exp) {
    487 	    Var_Append(MAKEOVERRIDES, exp, VAR_GLOBAL);
    488 	    if (exp != tmp)
    489 		free(exp);
    490 	}
    491     }
    492     if (name != cp)
    493 	free(name);
    494 }
    495 
    496 /*-
    497  *-----------------------------------------------------------------------
    498  * Var_Append --
    499  *	The variable of the given name has the given value appended to it in
    500  *	the given context.
    501  *
    502  * Results:
    503  *	None
    504  *
    505  * Side Effects:
    506  *	If the variable doesn't exist, it is created. Else the strings
    507  *	are concatenated (with a space in between).
    508  *
    509  * Notes:
    510  *	Only if the variable is being sought in the global context is the
    511  *	environment searched.
    512  *	XXX: Knows its calling circumstances in that if called with ctxt
    513  *	an actual target, it will only search that context since only
    514  *	a local variable could be being appended to. This is actually
    515  *	a big win and must be tolerated.
    516  *-----------------------------------------------------------------------
    517  */
    518 void
    519 Var_Append (name, val, ctxt)
    520     char           *name;	/* Name of variable to modify */
    521     char           *val;	/* String to append to it */
    522     GNode          *ctxt;	/* Context in which this should occur */
    523 {
    524     register Var   *v;
    525     Hash_Entry	   *h;
    526     char *cp = name;
    527 
    528     if ((name = strchr(cp, '$'))) {
    529 	name = Var_Subst(NULL, cp, ctxt, 0);
    530     } else
    531 	name = cp;
    532 
    533     v = VarFind (name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
    534 
    535     if (v == (Var *) NIL) {
    536 	VarAdd (name, val, ctxt);
    537     } else {
    538 	Buf_AddByte(v->val, (Byte)' ');
    539 	Buf_AddBytes(v->val, strlen(val), (Byte *)val);
    540 
    541 	if (DEBUG(VAR)) {
    542 	    printf("%s:%s = %s\n", ctxt->name, name,
    543 		   (char *) Buf_GetAll(v->val, (int *)NULL));
    544 	}
    545 
    546 	if (v->flags & VAR_FROM_ENV) {
    547 	    /*
    548 	     * If the original variable came from the environment, we
    549 	     * have to install it in the global context (we could place
    550 	     * it in the environment, but then we should provide a way to
    551 	     * export other variables...)
    552 	     */
    553 	    v->flags &= ~VAR_FROM_ENV;
    554 	    h = Hash_CreateEntry (&ctxt->context, name, NULL);
    555 	    Hash_SetValue(h, v);
    556 	}
    557     }
    558     if (name != cp)
    559 	free(name);
    560 }
    561 
    562 /*-
    563  *-----------------------------------------------------------------------
    564  * Var_Exists --
    565  *	See if the given variable exists.
    566  *
    567  * Results:
    568  *	TRUE if it does, FALSE if it doesn't
    569  *
    570  * Side Effects:
    571  *	None.
    572  *
    573  *-----------------------------------------------------------------------
    574  */
    575 Boolean
    576 Var_Exists(name, ctxt)
    577     char	  *name;    	/* Variable to find */
    578     GNode	  *ctxt;    	/* Context in which to start search */
    579 {
    580     Var	    	  *v;
    581 
    582     v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
    583 
    584     if (v == (Var *)NIL) {
    585 	return(FALSE);
    586     } else if (v->flags & VAR_FROM_ENV) {
    587 	free(v->name);
    588 	Buf_Destroy(v->val, TRUE);
    589 	free((char *)v);
    590     }
    591     return(TRUE);
    592 }
    593 
    594 /*-
    595  *-----------------------------------------------------------------------
    596  * Var_Value --
    597  *	Return the value of the named variable in the given context
    598  *
    599  * Results:
    600  *	The value if the variable exists, NULL if it doesn't
    601  *
    602  * Side Effects:
    603  *	None
    604  *-----------------------------------------------------------------------
    605  */
    606 char *
    607 Var_Value (name, ctxt, frp)
    608     char           *name;	/* name to find */
    609     GNode          *ctxt;	/* context in which to search for it */
    610     char	   **frp;
    611 {
    612     Var            *v;
    613 
    614     v = VarFind (name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
    615     *frp = NULL;
    616     if (v != (Var *) NIL) {
    617 	char *p = ((char *)Buf_GetAll(v->val, (int *)NULL));
    618 	if (v->flags & VAR_FROM_ENV) {
    619 	    free(v->name);
    620 	    Buf_Destroy(v->val, FALSE);
    621 	    free((Address) v);
    622 	    *frp = p;
    623 	}
    624 	return p;
    625     } else {
    626 	return ((char *) NULL);
    627     }
    628 }
    629 
    630 /*-
    631  *-----------------------------------------------------------------------
    632  * VarHead --
    633  *	Remove the tail of the given word and place the result in the given
    634  *	buffer.
    635  *
    636  * Results:
    637  *	TRUE if characters were added to the buffer (a space needs to be
    638  *	added to the buffer before the next word).
    639  *
    640  * Side Effects:
    641  *	The trimmed word is added to the buffer.
    642  *
    643  *-----------------------------------------------------------------------
    644  */
    645 static Boolean
    646 VarHead (ctx, word, addSpace, buf, dummy)
    647     GNode	  *ctx;
    648     char    	  *word;    	/* Word to trim */
    649     Boolean 	  addSpace; 	/* True if need to add a space to the buffer
    650 				 * before sticking in the head */
    651     Buffer  	  buf;	    	/* Buffer in which to store it */
    652     ClientData	  dummy;
    653 {
    654     register char *slash;
    655 
    656     slash = strrchr (word, '/');
    657     if (slash != (char *)NULL) {
    658 	if (addSpace) {
    659 	    Buf_AddByte (buf, (Byte)' ');
    660 	}
    661 	*slash = '\0';
    662 	Buf_AddBytes (buf, strlen (word), (Byte *)word);
    663 	*slash = '/';
    664 	return (TRUE);
    665     } else {
    666 	/*
    667 	 * If no directory part, give . (q.v. the POSIX standard)
    668 	 */
    669 	if (addSpace) {
    670 	    Buf_AddBytes(buf, 2, (Byte *)" .");
    671 	} else {
    672 	    Buf_AddByte(buf, (Byte)'.');
    673 	}
    674     }
    675     return(dummy ? TRUE : TRUE);
    676 }
    677 
    678 /*-
    679  *-----------------------------------------------------------------------
    680  * VarTail --
    681  *	Remove the head of the given word and place the result in the given
    682  *	buffer.
    683  *
    684  * Results:
    685  *	TRUE if characters were added to the buffer (a space needs to be
    686  *	added to the buffer before the next word).
    687  *
    688  * Side Effects:
    689  *	The trimmed word is added to the buffer.
    690  *
    691  *-----------------------------------------------------------------------
    692  */
    693 static Boolean
    694 VarTail (ctx, word, addSpace, buf, dummy)
    695     GNode	  *ctx;
    696     char    	  *word;    	/* Word to trim */
    697     Boolean 	  addSpace; 	/* TRUE if need to stick a space in the
    698 				 * buffer before adding the tail */
    699     Buffer  	  buf;	    	/* Buffer in which to store it */
    700     ClientData	  dummy;
    701 {
    702     register char *slash;
    703 
    704     if (addSpace) {
    705 	Buf_AddByte (buf, (Byte)' ');
    706     }
    707 
    708     slash = strrchr (word, '/');
    709     if (slash != (char *)NULL) {
    710 	*slash++ = '\0';
    711 	Buf_AddBytes (buf, strlen(slash), (Byte *)slash);
    712 	slash[-1] = '/';
    713     } else {
    714 	Buf_AddBytes (buf, strlen(word), (Byte *)word);
    715     }
    716     return (dummy ? TRUE : TRUE);
    717 }
    718 
    719 /*-
    720  *-----------------------------------------------------------------------
    721  * VarSuffix --
    722  *	Place the suffix of the given word in the given buffer.
    723  *
    724  * Results:
    725  *	TRUE if characters were added to the buffer (a space needs to be
    726  *	added to the buffer before the next word).
    727  *
    728  * Side Effects:
    729  *	The suffix from the word is placed in the buffer.
    730  *
    731  *-----------------------------------------------------------------------
    732  */
    733 static Boolean
    734 VarSuffix (ctx, word, addSpace, buf, dummy)
    735     GNode	  *ctx;
    736     char    	  *word;    	/* Word to trim */
    737     Boolean 	  addSpace; 	/* TRUE if need to add a space before placing
    738 				 * the suffix in the buffer */
    739     Buffer  	  buf;	    	/* Buffer in which to store it */
    740     ClientData	  dummy;
    741 {
    742     register char *dot;
    743 
    744     dot = strrchr (word, '.');
    745     if (dot != (char *)NULL) {
    746 	if (addSpace) {
    747 	    Buf_AddByte (buf, (Byte)' ');
    748 	}
    749 	*dot++ = '\0';
    750 	Buf_AddBytes (buf, strlen (dot), (Byte *)dot);
    751 	dot[-1] = '.';
    752 	addSpace = TRUE;
    753     }
    754     return (dummy ? addSpace : addSpace);
    755 }
    756 
    757 /*-
    758  *-----------------------------------------------------------------------
    759  * VarRoot --
    760  *	Remove the suffix of the given word and place the result in the
    761  *	buffer.
    762  *
    763  * Results:
    764  *	TRUE if characters were added to the buffer (a space needs to be
    765  *	added to the buffer before the next word).
    766  *
    767  * Side Effects:
    768  *	The trimmed word is added to the buffer.
    769  *
    770  *-----------------------------------------------------------------------
    771  */
    772 static Boolean
    773 VarRoot (ctx, word, addSpace, buf, dummy)
    774     GNode	  *ctx;
    775     char    	  *word;    	/* Word to trim */
    776     Boolean 	  addSpace; 	/* TRUE if need to add a space to the buffer
    777 				 * before placing the root in it */
    778     Buffer  	  buf;	    	/* Buffer in which to store it */
    779     ClientData	  dummy;
    780 {
    781     register char *dot;
    782 
    783     if (addSpace) {
    784 	Buf_AddByte (buf, (Byte)' ');
    785     }
    786 
    787     dot = strrchr (word, '.');
    788     if (dot != (char *)NULL) {
    789 	*dot = '\0';
    790 	Buf_AddBytes (buf, strlen (word), (Byte *)word);
    791 	*dot = '.';
    792     } else {
    793 	Buf_AddBytes (buf, strlen(word), (Byte *)word);
    794     }
    795     return (dummy ? TRUE : TRUE);
    796 }
    797 
    798 /*-
    799  *-----------------------------------------------------------------------
    800  * VarMatch --
    801  *	Place the word in the buffer if it matches the given pattern.
    802  *	Callback function for VarModify to implement the :M modifier.
    803  *
    804  * Results:
    805  *	TRUE if a space should be placed in the buffer before the next
    806  *	word.
    807  *
    808  * Side Effects:
    809  *	The word may be copied to the buffer.
    810  *
    811  *-----------------------------------------------------------------------
    812  */
    813 static Boolean
    814 VarMatch (ctx, word, addSpace, buf, pattern)
    815     GNode	  *ctx;
    816     char    	  *word;    	/* Word to examine */
    817     Boolean 	  addSpace; 	/* TRUE if need to add a space to the
    818 				 * buffer before adding the word, if it
    819 				 * matches */
    820     Buffer  	  buf;	    	/* Buffer in which to store it */
    821     ClientData    pattern; 	/* Pattern the word must match */
    822 {
    823     if (Str_Match(word, (char *) pattern)) {
    824 	if (addSpace) {
    825 	    Buf_AddByte(buf, (Byte)' ');
    826 	}
    827 	addSpace = TRUE;
    828 	Buf_AddBytes(buf, strlen(word), (Byte *)word);
    829     }
    830     return(addSpace);
    831 }
    832 
    833 #ifdef SYSVVARSUB
    834 /*-
    835  *-----------------------------------------------------------------------
    836  * VarSYSVMatch --
    837  *	Place the word in the buffer if it matches the given pattern.
    838  *	Callback function for VarModify to implement the System V %
    839  *	modifiers.
    840  *
    841  * Results:
    842  *	TRUE if a space should be placed in the buffer before the next
    843  *	word.
    844  *
    845  * Side Effects:
    846  *	The word may be copied to the buffer.
    847  *
    848  *-----------------------------------------------------------------------
    849  */
    850 static Boolean
    851 VarSYSVMatch (ctx, word, addSpace, buf, patp)
    852     GNode	  *ctx;
    853     char    	  *word;    	/* Word to examine */
    854     Boolean 	  addSpace; 	/* TRUE if need to add a space to the
    855 				 * buffer before adding the word, if it
    856 				 * matches */
    857     Buffer  	  buf;	    	/* Buffer in which to store it */
    858     ClientData 	  patp; 	/* Pattern the word must match */
    859 {
    860     int len;
    861     char *ptr;
    862     VarPattern 	  *pat = (VarPattern *) patp;
    863     char *varexp;
    864 
    865     if (addSpace)
    866 	Buf_AddByte(buf, (Byte)' ');
    867 
    868     addSpace = TRUE;
    869 
    870     if ((ptr = Str_SYSVMatch(word, pat->lhs, &len)) != NULL) {
    871         varexp = Var_Subst(NULL, pat->rhs, ctx, 0);
    872 	Str_SYSVSubst(buf, varexp, ptr, len);
    873 	free(varexp);
    874     } else {
    875 	Buf_AddBytes(buf, strlen(word), (Byte *) word);
    876     }
    877 
    878     return(addSpace);
    879 }
    880 #endif
    881 
    882 
    883 /*-
    884  *-----------------------------------------------------------------------
    885  * VarNoMatch --
    886  *	Place the word in the buffer if it doesn't match the given pattern.
    887  *	Callback function for VarModify to implement the :N modifier.
    888  *
    889  * Results:
    890  *	TRUE if a space should be placed in the buffer before the next
    891  *	word.
    892  *
    893  * Side Effects:
    894  *	The word may be copied to the buffer.
    895  *
    896  *-----------------------------------------------------------------------
    897  */
    898 static Boolean
    899 VarNoMatch (ctx, word, addSpace, buf, pattern)
    900     GNode	  *ctx;
    901     char    	  *word;    	/* Word to examine */
    902     Boolean 	  addSpace; 	/* TRUE if need to add a space to the
    903 				 * buffer before adding the word, if it
    904 				 * matches */
    905     Buffer  	  buf;	    	/* Buffer in which to store it */
    906     ClientData    pattern; 	/* Pattern the word must match */
    907 {
    908     if (!Str_Match(word, (char *) pattern)) {
    909 	if (addSpace) {
    910 	    Buf_AddByte(buf, (Byte)' ');
    911 	}
    912 	addSpace = TRUE;
    913 	Buf_AddBytes(buf, strlen(word), (Byte *)word);
    914     }
    915     return(addSpace);
    916 }
    917 
    918 
    919 /*-
    920  *-----------------------------------------------------------------------
    921  * VarSubstitute --
    922  *	Perform a string-substitution on the given word, placing the
    923  *	result in the passed buffer.
    924  *
    925  * Results:
    926  *	TRUE if a space is needed before more characters are added.
    927  *
    928  * Side Effects:
    929  *	None.
    930  *
    931  *-----------------------------------------------------------------------
    932  */
    933 static Boolean
    934 VarSubstitute (ctx, word, addSpace, buf, patternp)
    935     GNode		*ctx;
    936     char    	  	*word;	    /* Word to modify */
    937     Boolean 	  	addSpace;   /* True if space should be added before
    938 				     * other characters */
    939     Buffer  	  	buf;	    /* Buffer for result */
    940     ClientData	        patternp;   /* Pattern for substitution */
    941 {
    942     register int  	wordLen;    /* Length of word */
    943     register char 	*cp;	    /* General pointer */
    944     VarPattern	*pattern = (VarPattern *) patternp;
    945 
    946     wordLen = strlen(word);
    947     if ((pattern->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) !=
    948 	(VAR_SUB_ONE|VAR_SUB_MATCHED)) {
    949 	/*
    950 	 * Still substituting -- break it down into simple anchored cases
    951 	 * and if none of them fits, perform the general substitution case.
    952 	 */
    953 	if ((pattern->flags & VAR_MATCH_START) &&
    954 	    (strncmp(word, pattern->lhs, pattern->leftLen) == 0)) {
    955 		/*
    956 		 * Anchored at start and beginning of word matches pattern
    957 		 */
    958 		if ((pattern->flags & VAR_MATCH_END) &&
    959 		    (wordLen == pattern->leftLen)) {
    960 			/*
    961 			 * Also anchored at end and matches to the end (word
    962 			 * is same length as pattern) add space and rhs only
    963 			 * if rhs is non-null.
    964 			 */
    965 			if (pattern->rightLen != 0) {
    966 			    if (addSpace) {
    967 				Buf_AddByte(buf, (Byte)' ');
    968 			    }
    969 			    addSpace = TRUE;
    970 			    Buf_AddBytes(buf, pattern->rightLen,
    971 					 (Byte *)pattern->rhs);
    972 			}
    973 			pattern->flags |= VAR_SUB_MATCHED;
    974 		} else if (pattern->flags & VAR_MATCH_END) {
    975 		    /*
    976 		     * Doesn't match to end -- copy word wholesale
    977 		     */
    978 		    goto nosub;
    979 		} else {
    980 		    /*
    981 		     * Matches at start but need to copy in trailing characters
    982 		     */
    983 		    if ((pattern->rightLen + wordLen - pattern->leftLen) != 0){
    984 			if (addSpace) {
    985 			    Buf_AddByte(buf, (Byte)' ');
    986 			}
    987 			addSpace = TRUE;
    988 		    }
    989 		    Buf_AddBytes(buf, pattern->rightLen, (Byte *)pattern->rhs);
    990 		    Buf_AddBytes(buf, wordLen - pattern->leftLen,
    991 				 (Byte *)(word + pattern->leftLen));
    992 		    pattern->flags |= VAR_SUB_MATCHED;
    993 		}
    994 	} else if (pattern->flags & VAR_MATCH_START) {
    995 	    /*
    996 	     * Had to match at start of word and didn't -- copy whole word.
    997 	     */
    998 	    goto nosub;
    999 	} else if (pattern->flags & VAR_MATCH_END) {
   1000 	    /*
   1001 	     * Anchored at end, Find only place match could occur (leftLen
   1002 	     * characters from the end of the word) and see if it does. Note
   1003 	     * that because the $ will be left at the end of the lhs, we have
   1004 	     * to use strncmp.
   1005 	     */
   1006 	    cp = word + (wordLen - pattern->leftLen);
   1007 	    if ((cp >= word) &&
   1008 		(strncmp(cp, pattern->lhs, pattern->leftLen) == 0)) {
   1009 		/*
   1010 		 * Match found. If we will place characters in the buffer,
   1011 		 * add a space before hand as indicated by addSpace, then
   1012 		 * stuff in the initial, unmatched part of the word followed
   1013 		 * by the right-hand-side.
   1014 		 */
   1015 		if (((cp - word) + pattern->rightLen) != 0) {
   1016 		    if (addSpace) {
   1017 			Buf_AddByte(buf, (Byte)' ');
   1018 		    }
   1019 		    addSpace = TRUE;
   1020 		}
   1021 		Buf_AddBytes(buf, cp - word, (Byte *)word);
   1022 		Buf_AddBytes(buf, pattern->rightLen, (Byte *)pattern->rhs);
   1023 		pattern->flags |= VAR_SUB_MATCHED;
   1024 	    } else {
   1025 		/*
   1026 		 * Had to match at end and didn't. Copy entire word.
   1027 		 */
   1028 		goto nosub;
   1029 	    }
   1030 	} else {
   1031 	    /*
   1032 	     * Pattern is unanchored: search for the pattern in the word using
   1033 	     * String_FindSubstring, copying unmatched portions and the
   1034 	     * right-hand-side for each match found, handling non-global
   1035 	     * substitutions correctly, etc. When the loop is done, any
   1036 	     * remaining part of the word (word and wordLen are adjusted
   1037 	     * accordingly through the loop) is copied straight into the
   1038 	     * buffer.
   1039 	     * addSpace is set FALSE as soon as a space is added to the
   1040 	     * buffer.
   1041 	     */
   1042 	    register Boolean done;
   1043 	    int origSize;
   1044 
   1045 	    done = FALSE;
   1046 	    origSize = Buf_Size(buf);
   1047 	    while (!done) {
   1048 		cp = Str_FindSubstring(word, pattern->lhs);
   1049 		if (cp != (char *)NULL) {
   1050 		    if (addSpace && (((cp - word) + pattern->rightLen) != 0)){
   1051 			Buf_AddByte(buf, (Byte)' ');
   1052 			addSpace = FALSE;
   1053 		    }
   1054 		    Buf_AddBytes(buf, cp-word, (Byte *)word);
   1055 		    Buf_AddBytes(buf, pattern->rightLen, (Byte *)pattern->rhs);
   1056 		    wordLen -= (cp - word) + pattern->leftLen;
   1057 		    word = cp + pattern->leftLen;
   1058 		    if (wordLen == 0) {
   1059 			done = TRUE;
   1060 		    }
   1061 		    if ((pattern->flags & VAR_SUB_GLOBAL) == 0) {
   1062 			done = TRUE;
   1063 		    }
   1064 		    pattern->flags |= VAR_SUB_MATCHED;
   1065 		} else {
   1066 		    done = TRUE;
   1067 		}
   1068 	    }
   1069 	    if (wordLen != 0) {
   1070 		if (addSpace) {
   1071 		    Buf_AddByte(buf, (Byte)' ');
   1072 		}
   1073 		Buf_AddBytes(buf, wordLen, (Byte *)word);
   1074 	    }
   1075 	    /*
   1076 	     * If added characters to the buffer, need to add a space
   1077 	     * before we add any more. If we didn't add any, just return
   1078 	     * the previous value of addSpace.
   1079 	     */
   1080 	    return ((Buf_Size(buf) != origSize) || addSpace);
   1081 	}
   1082 	return (addSpace);
   1083     }
   1084  nosub:
   1085     if (addSpace) {
   1086 	Buf_AddByte(buf, (Byte)' ');
   1087     }
   1088     Buf_AddBytes(buf, wordLen, (Byte *)word);
   1089     return(TRUE);
   1090 }
   1091 
   1092 #ifndef NO_REGEX
   1093 /*-
   1094  *-----------------------------------------------------------------------
   1095  * VarREError --
   1096  *	Print the error caused by a regcomp or regexec call.
   1097  *
   1098  * Results:
   1099  *	None.
   1100  *
   1101  * Side Effects:
   1102  *	An error gets printed.
   1103  *
   1104  *-----------------------------------------------------------------------
   1105  */
   1106 static void
   1107 VarREError(err, pat, str)
   1108     int err;
   1109     regex_t *pat;
   1110     const char *str;
   1111 {
   1112     char *errbuf;
   1113     int errlen;
   1114 
   1115     errlen = regerror(err, pat, 0, 0);
   1116     errbuf = emalloc(errlen);
   1117     regerror(err, pat, errbuf, errlen);
   1118     Error("%s: %s", str, errbuf);
   1119     free(errbuf);
   1120 }
   1121 
   1122 
   1123 /*-
   1124  *-----------------------------------------------------------------------
   1125  * VarRESubstitute --
   1126  *	Perform a regex substitution on the given word, placing the
   1127  *	result in the passed buffer.
   1128  *
   1129  * Results:
   1130  *	TRUE if a space is needed before more characters are added.
   1131  *
   1132  * Side Effects:
   1133  *	None.
   1134  *
   1135  *-----------------------------------------------------------------------
   1136  */
   1137 static Boolean
   1138 VarRESubstitute(ctx, word, addSpace, buf, patternp)
   1139     GNode *ctx;
   1140     char *word;
   1141     Boolean addSpace;
   1142     Buffer buf;
   1143     ClientData patternp;
   1144 {
   1145     VarREPattern *pat;
   1146     int xrv;
   1147     char *wp;
   1148     char *rp;
   1149     int added;
   1150     int flags = 0;
   1151 
   1152 #define MAYBE_ADD_SPACE()		\
   1153 	if (addSpace && !added)		\
   1154 	    Buf_AddByte(buf, ' ');	\
   1155 	added = 1
   1156 
   1157     added = 0;
   1158     wp = word;
   1159     pat = patternp;
   1160 
   1161     if ((pat->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) ==
   1162 	(VAR_SUB_ONE|VAR_SUB_MATCHED))
   1163 	xrv = REG_NOMATCH;
   1164     else {
   1165     tryagain:
   1166 	xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
   1167     }
   1168 
   1169     switch (xrv) {
   1170     case 0:
   1171 	pat->flags |= VAR_SUB_MATCHED;
   1172 	if (pat->matches[0].rm_so > 0) {
   1173 	    MAYBE_ADD_SPACE();
   1174 	    Buf_AddBytes(buf, pat->matches[0].rm_so, wp);
   1175 	}
   1176 
   1177 	for (rp = pat->replace; *rp; rp++) {
   1178 	    if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
   1179 		MAYBE_ADD_SPACE();
   1180 		Buf_AddByte(buf,rp[1]);
   1181 		rp++;
   1182 	    }
   1183 	    else if ((*rp == '&') ||
   1184 		((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
   1185 		int n;
   1186 		char *subbuf;
   1187 		int sublen;
   1188 		char errstr[3];
   1189 
   1190 		if (*rp == '&') {
   1191 		    n = 0;
   1192 		    errstr[0] = '&';
   1193 		    errstr[1] = '\0';
   1194 		} else {
   1195 		    n = rp[1] - '0';
   1196 		    errstr[0] = '\\';
   1197 		    errstr[1] = rp[1];
   1198 		    errstr[2] = '\0';
   1199 		    rp++;
   1200 		}
   1201 
   1202 		if (n > pat->nsub) {
   1203 		    Error("No subexpression %s", &errstr[0]);
   1204 		    subbuf = "";
   1205 		    sublen = 0;
   1206 		} else if ((pat->matches[n].rm_so == -1) &&
   1207 			   (pat->matches[n].rm_eo == -1)) {
   1208 		    Error("No match for subexpression %s", &errstr[0]);
   1209 		    subbuf = "";
   1210 		    sublen = 0;
   1211 	        } else {
   1212 		    subbuf = wp + pat->matches[n].rm_so;
   1213 		    sublen = pat->matches[n].rm_eo - pat->matches[n].rm_so;
   1214 		}
   1215 
   1216 		if (sublen > 0) {
   1217 		    MAYBE_ADD_SPACE();
   1218 		    Buf_AddBytes(buf, sublen, subbuf);
   1219 		}
   1220 	    } else {
   1221 		MAYBE_ADD_SPACE();
   1222 		Buf_AddByte(buf, *rp);
   1223 	    }
   1224 	}
   1225 	wp += pat->matches[0].rm_eo;
   1226 	if (pat->flags & VAR_SUB_GLOBAL) {
   1227 	    flags |= REG_NOTBOL;
   1228 	    if (pat->matches[0].rm_so == 0 && pat->matches[0].rm_eo == 0) {
   1229 		MAYBE_ADD_SPACE();
   1230 		Buf_AddByte(buf, *wp);
   1231 		wp++;
   1232 
   1233 	    }
   1234 	    if (*wp)
   1235 		goto tryagain;
   1236 	}
   1237 	if (*wp) {
   1238 	    MAYBE_ADD_SPACE();
   1239 	    Buf_AddBytes(buf, strlen(wp), wp);
   1240 	}
   1241 	break;
   1242     default:
   1243 	VarREError(xrv, &pat->re, "Unexpected regex error");
   1244        /* fall through */
   1245     case REG_NOMATCH:
   1246 	if (*wp) {
   1247 	    MAYBE_ADD_SPACE();
   1248 	    Buf_AddBytes(buf,strlen(wp),wp);
   1249 	}
   1250 	break;
   1251     }
   1252     return(addSpace||added);
   1253 }
   1254 #endif
   1255 
   1256 
   1257 
   1258 /*-
   1259  *-----------------------------------------------------------------------
   1260  * VarLoopExpand --
   1261  *	Implements the :@<temp>@<string>@ modifier of ODE make.
   1262  *	We set the temp variable named in pattern.lhs to word and expand
   1263  *	pattern.rhs storing the result in the passed buffer.
   1264  *
   1265  * Results:
   1266  *	TRUE if a space is needed before more characters are added.
   1267  *
   1268  * Side Effects:
   1269  *	None.
   1270  *
   1271  *-----------------------------------------------------------------------
   1272  */
   1273 static Boolean
   1274 VarLoopExpand (ctx, word, addSpace, buf, loopp)
   1275     GNode		*ctx;
   1276     char    	  	*word;	    /* Word to modify */
   1277     Boolean 	  	addSpace;   /* True if space should be added before
   1278 				     * other characters */
   1279     Buffer  	  	buf;	    /* Buffer for result */
   1280     ClientData	        loopp;      /* Data for substitution */
   1281 {
   1282     VarLoop_t	*loop = (VarLoop_t *) loopp;
   1283     char *s;
   1284     int slen;
   1285 
   1286     Var_Set(loop->tvar, word, loop->ctxt);
   1287     s = Var_Subst(NULL, loop->str, loop->ctxt, loop->err);
   1288     if (s != NULL && *s != '\0') {
   1289 	if (addSpace && *s != '\n')
   1290 	    Buf_AddByte(buf, ' ');
   1291 	Buf_AddBytes(buf, (slen = strlen(s)), (Byte *)s);
   1292 	addSpace = (slen > 0 && s[slen - 1] != '\n');
   1293 	free(s);
   1294     }
   1295     return addSpace;
   1296 }
   1297 
   1298 /*-
   1299  *-----------------------------------------------------------------------
   1300  * VarModify --
   1301  *	Modify each of the words of the passed string using the given
   1302  *	function. Used to implement all modifiers.
   1303  *
   1304  * Results:
   1305  *	A string of all the words modified appropriately.
   1306  *
   1307  * Side Effects:
   1308  *	None.
   1309  *
   1310  *-----------------------------------------------------------------------
   1311  */
   1312 static char *
   1313 VarModify (ctx, str, modProc, datum)
   1314     GNode	  *ctx;
   1315     char    	  *str;	    	    /* String whose words should be trimmed */
   1316 				    /* Function to use to modify them */
   1317     Boolean    	  (*modProc) __P((GNode *, char *, Boolean, Buffer,
   1318 				  ClientData));
   1319     ClientData	  datum;    	    /* Datum to pass it */
   1320 {
   1321     Buffer  	  buf;	    	    /* Buffer for the new string */
   1322     Boolean 	  addSpace; 	    /* TRUE if need to add a space to the
   1323 				     * buffer before adding the trimmed
   1324 				     * word */
   1325     char **av;			    /* word list [first word does not count] */
   1326     char *as;			    /* word list memory */
   1327     int ac, i;
   1328 
   1329     buf = Buf_Init (0);
   1330     addSpace = FALSE;
   1331 
   1332     av = brk_string(str, &ac, FALSE, &as);
   1333 
   1334     for (i = 0; i < ac; i++)
   1335 	addSpace = (*modProc)(ctx, av[i], addSpace, buf, datum);
   1336 
   1337     free(as);
   1338     free(av);
   1339 
   1340     Buf_AddByte (buf, '\0');
   1341     str = (char *)Buf_GetAll (buf, (int *)NULL);
   1342     Buf_Destroy (buf, FALSE);
   1343     return (str);
   1344 }
   1345 
   1346 
   1347 static int
   1348 VarWordCompare(a, b)
   1349 	const void *a;
   1350 	const void *b;
   1351 {
   1352 	int r = strcmp(*(char **)a, *(char **)b);
   1353 	return r;
   1354 }
   1355 
   1356 /*-
   1357  *-----------------------------------------------------------------------
   1358  * VarSort --
   1359  *	Sort the words in the string.
   1360  *
   1361  * Results:
   1362  *	A string containing the words sorted
   1363  *
   1364  * Side Effects:
   1365  *	None.
   1366  *
   1367  *-----------------------------------------------------------------------
   1368  */
   1369 static char *
   1370 VarSort (str)
   1371     char    	  *str;	    	    /* String whose words should be sorted */
   1372 				    /* Function to use to modify them */
   1373 {
   1374     Buffer  	  buf;	    	    /* Buffer for the new string */
   1375     char **av;			    /* word list [first word does not count] */
   1376     char *as;			    /* word list memory */
   1377     int ac, i;
   1378 
   1379     buf = Buf_Init (0);
   1380 
   1381     av = brk_string(str, &ac, FALSE, &as);
   1382 
   1383     if (ac > 0)
   1384 	qsort(av, ac, sizeof(char *), VarWordCompare);
   1385 
   1386     for (i = 0; i < ac; i++) {
   1387 	Buf_AddBytes(buf, strlen(av[i]), (Byte *) av[i]);
   1388 	if (i != ac - 1)
   1389 	    Buf_AddByte (buf, ' ');
   1390     }
   1391 
   1392     free(as);
   1393     free(av);
   1394 
   1395     Buf_AddByte (buf, '\0');
   1396     str = (char *)Buf_GetAll (buf, (int *)NULL);
   1397     Buf_Destroy (buf, FALSE);
   1398     return (str);
   1399 }
   1400 
   1401 
   1402 /*-
   1403  *-----------------------------------------------------------------------
   1404  * VarUniq --
   1405  *	Remove adjacent duplicate words.
   1406  *
   1407  * Results:
   1408  *	A string containing the resulting words.
   1409  *
   1410  * Side Effects:
   1411  *	None.
   1412  *
   1413  *-----------------------------------------------------------------------
   1414  */
   1415 static char *
   1416 VarUniq(str)
   1417     char 	 *str;	    	    /* String whose words should be sorted */
   1418 				    /* Function to use to modify them */
   1419 {
   1420     Buffer	  buf;	    	    /* Buffer for new string */
   1421     char 	**av;		    /* List of words to affect */
   1422     char 	 *as;		    /* Word list memory */
   1423     int 	  ac, i, j;
   1424 
   1425     buf = Buf_Init(0);
   1426     av = brk_string(str, &ac, FALSE, &as);
   1427 
   1428     if (ac > 1) {
   1429 	for (j = 0, i = 1; i < ac; i++)
   1430 	    if (strcmp(av[i], av[j]) != 0 && (++j != i))
   1431 		av[j] = av[i];
   1432 	ac = j + 1;
   1433     }
   1434 
   1435     for (i = 0; i < ac; i++) {
   1436 	Buf_AddBytes(buf, strlen(av[i]), (Byte *)av[i]);
   1437 	if (i != ac - 1)
   1438 	    Buf_AddByte(buf, ' ');
   1439     }
   1440 
   1441     free(as);
   1442     free(av);
   1443 
   1444     Buf_AddByte(buf, '\0');
   1445     str = (char *)Buf_GetAll(buf, (int *)NULL);
   1446     Buf_Destroy(buf, FALSE);
   1447     return str;
   1448 }
   1449 
   1450 
   1451 /*-
   1452  *-----------------------------------------------------------------------
   1453  * VarGetPattern --
   1454  *	Pass through the tstr looking for 1) escaped delimiters,
   1455  *	'$'s and backslashes (place the escaped character in
   1456  *	uninterpreted) and 2) unescaped $'s that aren't before
   1457  *	the delimiter (expand the variable substitution unless flags
   1458  *	has VAR_NOSUBST set).
   1459  *	Return the expanded string or NULL if the delimiter was missing
   1460  *	If pattern is specified, handle escaped ampersands, and replace
   1461  *	unescaped ampersands with the lhs of the pattern.
   1462  *
   1463  * Results:
   1464  *	A string of all the words modified appropriately.
   1465  *	If length is specified, return the string length of the buffer
   1466  *	If flags is specified and the last character of the pattern is a
   1467  *	$ set the VAR_MATCH_END bit of flags.
   1468  *
   1469  * Side Effects:
   1470  *	None.
   1471  *-----------------------------------------------------------------------
   1472  */
   1473 static char *
   1474 VarGetPattern(ctxt, err, tstr, delim, flags, length, pattern)
   1475     GNode *ctxt;
   1476     int err;
   1477     char **tstr;
   1478     int delim;
   1479     int *flags;
   1480     int *length;
   1481     VarPattern *pattern;
   1482 {
   1483     char *cp;
   1484     Buffer buf = Buf_Init(0);
   1485     int junk;
   1486     if (length == NULL)
   1487 	length = &junk;
   1488 
   1489 #define IS_A_MATCH(cp, delim) \
   1490     ((cp[0] == '\\') && ((cp[1] == delim) ||  \
   1491      (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
   1492 
   1493     /*
   1494      * Skim through until the matching delimiter is found;
   1495      * pick up variable substitutions on the way. Also allow
   1496      * backslashes to quote the delimiter, $, and \, but don't
   1497      * touch other backslashes.
   1498      */
   1499     for (cp = *tstr; *cp && (*cp != delim); cp++) {
   1500 	if (IS_A_MATCH(cp, delim)) {
   1501 	    Buf_AddByte(buf, (Byte) cp[1]);
   1502 	    cp++;
   1503 	} else if (*cp == '$') {
   1504 	    if (cp[1] == delim) {
   1505 		if (flags == NULL)
   1506 		    Buf_AddByte(buf, (Byte) *cp);
   1507 		else
   1508 		    /*
   1509 		     * Unescaped $ at end of pattern => anchor
   1510 		     * pattern at end.
   1511 		     */
   1512 		    *flags |= VAR_MATCH_END;
   1513 	    } else {
   1514 		if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
   1515 		    char   *cp2;
   1516 		    int     len;
   1517 		    Boolean freeIt;
   1518 
   1519 		    /*
   1520 		     * If unescaped dollar sign not before the
   1521 		     * delimiter, assume it's a variable
   1522 		     * substitution and recurse.
   1523 		     */
   1524 		    cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
   1525 		    Buf_AddBytes(buf, strlen(cp2), (Byte *) cp2);
   1526 		    if (freeIt)
   1527 			free(cp2);
   1528 		    cp += len - 1;
   1529 		} else {
   1530 		    char *cp2 = &cp[1];
   1531 
   1532 		    if (*cp2 == '(' || *cp2 == '{') {
   1533 			/*
   1534 			 * Find the end of this variable reference
   1535 			 * and suck it in without further ado.
   1536 			 * It will be interperated later.
   1537 			 */
   1538 			int have = *cp2;
   1539 			int want = (*cp2 == '(') ? ')' : '}';
   1540 			int depth = 1;
   1541 
   1542 			for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
   1543 			    if (cp2[-1] != '\\') {
   1544 				if (*cp2 == have)
   1545 				    ++depth;
   1546 				if (*cp2 == want)
   1547 				    --depth;
   1548 			    }
   1549 			}
   1550 			Buf_AddBytes(buf, cp2 - cp, (Byte *)cp);
   1551 			cp = --cp2;
   1552 		    } else
   1553 			Buf_AddByte(buf, (Byte) *cp);
   1554 		}
   1555 	    }
   1556 	}
   1557 	else if (pattern && *cp == '&')
   1558 	    Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
   1559 	else
   1560 	    Buf_AddByte(buf, (Byte) *cp);
   1561     }
   1562 
   1563     Buf_AddByte(buf, (Byte) '\0');
   1564 
   1565     if (*cp != delim) {
   1566 	*tstr = cp;
   1567 	*length = 0;
   1568 	return NULL;
   1569     }
   1570     else {
   1571 	*tstr = ++cp;
   1572 	cp = (char *) Buf_GetAll(buf, length);
   1573 	*length -= 1;	/* Don't count the NULL */
   1574 	Buf_Destroy(buf, FALSE);
   1575 	return cp;
   1576     }
   1577 }
   1578 
   1579 /*-
   1580  *-----------------------------------------------------------------------
   1581  * VarQuote --
   1582  *	Quote shell meta-characters in the string
   1583  *
   1584  * Results:
   1585  *	The quoted string
   1586  *
   1587  * Side Effects:
   1588  *	None.
   1589  *
   1590  *-----------------------------------------------------------------------
   1591  */
   1592 static char *
   1593 VarQuote(str)
   1594 	char *str;
   1595 {
   1596 
   1597     Buffer  	  buf;
   1598     /* This should cover most shells :-( */
   1599     static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
   1600 
   1601     buf = Buf_Init (MAKE_BSIZE);
   1602     for (; *str; str++) {
   1603 	if (strchr(meta, *str) != NULL)
   1604 	    Buf_AddByte(buf, (Byte)'\\');
   1605 	Buf_AddByte(buf, (Byte)*str);
   1606     }
   1607     Buf_AddByte(buf, (Byte) '\0');
   1608     str = (char *)Buf_GetAll (buf, (int *)NULL);
   1609     Buf_Destroy (buf, FALSE);
   1610     return str;
   1611 }
   1612 
   1613 
   1614 /*-
   1615  *-----------------------------------------------------------------------
   1616  * Var_Parse --
   1617  *	Given the start of a variable invocation, extract the variable
   1618  *	name and find its value, then modify it according to the
   1619  *	specification.
   1620  *
   1621  * Results:
   1622  *	The (possibly-modified) value of the variable or var_Error if the
   1623  *	specification is invalid. The length of the specification is
   1624  *	placed in *lengthPtr (for invalid specifications, this is just
   1625  *	2...?).
   1626  *	A Boolean in *freePtr telling whether the returned string should
   1627  *	be freed by the caller.
   1628  *
   1629  * Side Effects:
   1630  *	None.
   1631  *
   1632  *-----------------------------------------------------------------------
   1633  */
   1634 char *
   1635 Var_Parse (str, ctxt, err, lengthPtr, freePtr)
   1636     char    	  *str;	    	/* The string to parse */
   1637     GNode   	  *ctxt;    	/* The context for the variable */
   1638     Boolean 	    err;    	/* TRUE if undefined variables are an error */
   1639     int	    	    *lengthPtr;	/* OUT: The length of the specification */
   1640     Boolean 	    *freePtr; 	/* OUT: TRUE if caller should free result */
   1641 {
   1642     register char   *tstr;    	/* Pointer into str */
   1643     Var	    	    *v;	    	/* Variable in invocation */
   1644     char   	    *cp;    	/* Secondary pointer into str (place marker
   1645 				 * for tstr) */
   1646     Boolean 	    haveModifier;/* TRUE if have modifiers for the variable */
   1647     register char   endc;    	/* Ending character when variable in parens
   1648 				 * or braces */
   1649     register char   startc=0;	/* Starting character when variable in parens
   1650 				 * or braces */
   1651     int             cnt;	/* Used to count brace pairs when variable in
   1652 				 * in parens or braces */
   1653     int		    vlen;	/* Length of variable name */
   1654     char    	    *start;
   1655     char	     delim;
   1656     Boolean 	    dynamic;	/* TRUE if the variable is local and we're
   1657 				 * expanding it in a non-local context. This
   1658 				 * is done to support dynamic sources. The
   1659 				 * result is just the invocation, unaltered */
   1660 
   1661     *freePtr = FALSE;
   1662     dynamic = FALSE;
   1663     start = str;
   1664 
   1665     if (str[1] != '(' && str[1] != '{') {
   1666 	/*
   1667 	 * If it's not bounded by braces of some sort, life is much simpler.
   1668 	 * We just need to check for the first character and return the
   1669 	 * value if it exists.
   1670 	 */
   1671 	char	  name[2];
   1672 
   1673 	name[0] = str[1];
   1674 	name[1] = '\0';
   1675 
   1676 	v = VarFind (name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
   1677 	if (v == (Var *)NIL) {
   1678 	    *lengthPtr = 2;
   1679 
   1680 	    if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
   1681 		/*
   1682 		 * If substituting a local variable in a non-local context,
   1683 		 * assume it's for dynamic source stuff. We have to handle
   1684 		 * this specially and return the longhand for the variable
   1685 		 * with the dollar sign escaped so it makes it back to the
   1686 		 * caller. Only four of the local variables are treated
   1687 		 * specially as they are the only four that will be set
   1688 		 * when dynamic sources are expanded.
   1689 		 */
   1690 		switch (str[1]) {
   1691 		    case '@':
   1692 			return("$(.TARGET)");
   1693 		    case '%':
   1694 			return("$(.ARCHIVE)");
   1695 		    case '*':
   1696 			return("$(.PREFIX)");
   1697 		    case '!':
   1698 			return("$(.MEMBER)");
   1699 		}
   1700 	    }
   1701 	    /*
   1702 	     * Error
   1703 	     */
   1704 	    return (err ? var_Error : varNoError);
   1705 	} else {
   1706 	    haveModifier = FALSE;
   1707 	    tstr = &str[1];
   1708 	    endc = str[1];
   1709 	}
   1710     } else {
   1711 	Buffer buf;	/* Holds the variable name */
   1712 
   1713 	startc = str[1];
   1714 	endc = startc == '(' ? ')' : '}';
   1715 	buf = Buf_Init (MAKE_BSIZE);
   1716 
   1717 	/*
   1718 	 * Skip to the end character or a colon, whichever comes first.
   1719 	 */
   1720 	for (tstr = str + 2;
   1721 	     *tstr != '\0' && *tstr != endc && *tstr != ':';
   1722 	     tstr++)
   1723 	{
   1724 	    /*
   1725 	     * A variable inside a variable, expand
   1726 	     */
   1727 	    if (*tstr == '$') {
   1728 		int rlen;
   1729 		Boolean rfree;
   1730 		char *rval = Var_Parse(tstr, ctxt, err, &rlen, &rfree);
   1731 		if (rval != NULL) {
   1732 		    Buf_AddBytes(buf, strlen(rval), (Byte *) rval);
   1733 		    if (rfree)
   1734 			free(rval);
   1735 		}
   1736 		tstr += rlen - 1;
   1737 	    }
   1738 	    else
   1739 		Buf_AddByte(buf, (Byte) *tstr);
   1740 	}
   1741 	if (*tstr == ':') {
   1742 	    haveModifier = TRUE;
   1743 	} else if (*tstr != '\0') {
   1744 	    haveModifier = FALSE;
   1745 	} else {
   1746 	    /*
   1747 	     * If we never did find the end character, return NULL
   1748 	     * right now, setting the length to be the distance to
   1749 	     * the end of the string, since that's what make does.
   1750 	     */
   1751 	    *lengthPtr = tstr - str;
   1752 	    return (var_Error);
   1753 	}
   1754 	*tstr = '\0';
   1755 	Buf_AddByte(buf, (Byte) '\0');
   1756 	str = Buf_GetAll(buf, (int *) NULL);
   1757 	vlen = strlen(str);
   1758 
   1759 	v = VarFind (str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
   1760 	if ((v == (Var *)NIL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
   1761 	    (vlen == 2) && (str[1] == 'F' || str[1] == 'D'))
   1762 	{
   1763 	    /*
   1764 	     * Check for bogus D and F forms of local variables since we're
   1765 	     * in a local context and the name is the right length.
   1766 	     */
   1767 	    switch(*str) {
   1768 		case '@':
   1769 		case '%':
   1770 		case '*':
   1771 		case '!':
   1772 		case '>':
   1773 		case '<':
   1774 		{
   1775 		    char    vname[2];
   1776 		    char    *val;
   1777 
   1778 		    /*
   1779 		     * Well, it's local -- go look for it.
   1780 		     */
   1781 		    vname[0] = *str;
   1782 		    vname[1] = '\0';
   1783 		    v = VarFind(vname, ctxt, 0);
   1784 
   1785 		    if (v != (Var *)NIL) {
   1786 			/*
   1787 			 * No need for nested expansion or anything, as we're
   1788 			 * the only one who sets these things and we sure don't
   1789 			 * but nested invocations in them...
   1790 			 */
   1791 			val = (char *)Buf_GetAll(v->val, (int *)NULL);
   1792 
   1793 			if (str[1] == 'D') {
   1794 			    val = VarModify(ctxt, val, VarHead, (ClientData)0);
   1795 			} else {
   1796 			    val = VarModify(ctxt, val, VarTail, (ClientData)0);
   1797 			}
   1798 			/*
   1799 			 * Resulting string is dynamically allocated, so
   1800 			 * tell caller to free it.
   1801 			 */
   1802 			*freePtr = TRUE;
   1803 			*lengthPtr = tstr-start+1;
   1804 			*tstr = endc;
   1805 			Buf_Destroy (buf, TRUE);
   1806 			return(val);
   1807 		    }
   1808 		    break;
   1809 		}
   1810 	    }
   1811 	}
   1812 
   1813 	if (v == (Var *)NIL) {
   1814 	    if (((vlen == 1) ||
   1815 		 (((vlen == 2) && (str[1] == 'F' ||
   1816 					 str[1] == 'D')))) &&
   1817 		((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
   1818 	    {
   1819 		/*
   1820 		 * If substituting a local variable in a non-local context,
   1821 		 * assume it's for dynamic source stuff. We have to handle
   1822 		 * this specially and return the longhand for the variable
   1823 		 * with the dollar sign escaped so it makes it back to the
   1824 		 * caller. Only four of the local variables are treated
   1825 		 * specially as they are the only four that will be set
   1826 		 * when dynamic sources are expanded.
   1827 		 */
   1828 		switch (*str) {
   1829 		    case '@':
   1830 		    case '%':
   1831 		    case '*':
   1832 		    case '!':
   1833 			dynamic = TRUE;
   1834 			break;
   1835 		}
   1836 	    } else if ((vlen > 2) && (*str == '.') &&
   1837 		       isupper((unsigned char) str[1]) &&
   1838 		       ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
   1839 	    {
   1840 		int	len;
   1841 
   1842 		len = vlen - 1;
   1843 		if ((strncmp(str, ".TARGET", len) == 0) ||
   1844 		    (strncmp(str, ".ARCHIVE", len) == 0) ||
   1845 		    (strncmp(str, ".PREFIX", len) == 0) ||
   1846 		    (strncmp(str, ".MEMBER", len) == 0))
   1847 		{
   1848 		    dynamic = TRUE;
   1849 		}
   1850 	    }
   1851 
   1852 	    if (!haveModifier) {
   1853 		/*
   1854 		 * No modifiers -- have specification length so we can return
   1855 		 * now.
   1856 		 */
   1857 		*lengthPtr = tstr - start + 1;
   1858 		*tstr = endc;
   1859 		if (dynamic) {
   1860 		    str = emalloc(*lengthPtr + 1);
   1861 		    strncpy(str, start, *lengthPtr);
   1862 		    str[*lengthPtr] = '\0';
   1863 		    *freePtr = TRUE;
   1864 		    Buf_Destroy (buf, TRUE);
   1865 		    return(str);
   1866 		} else {
   1867 		    Buf_Destroy (buf, TRUE);
   1868 		    return (err ? var_Error : varNoError);
   1869 		}
   1870 	    } else {
   1871 		/*
   1872 		 * Still need to get to the end of the variable specification,
   1873 		 * so kludge up a Var structure for the modifications
   1874 		 */
   1875 		v = (Var *) emalloc(sizeof(Var));
   1876 		v->name = str;
   1877 		v->val = Buf_Init(1);
   1878 		v->flags = VAR_JUNK;
   1879 		Buf_Destroy (buf, FALSE);
   1880 	    }
   1881 	} else
   1882 	    Buf_Destroy (buf, TRUE);
   1883     }
   1884 
   1885 
   1886     if (v->flags & VAR_IN_USE) {
   1887 	Fatal("Variable %s is recursive.", v->name);
   1888 	/*NOTREACHED*/
   1889     } else {
   1890 	v->flags |= VAR_IN_USE;
   1891     }
   1892     /*
   1893      * Before doing any modification, we have to make sure the value
   1894      * has been fully expanded. If it looks like recursion might be
   1895      * necessary (there's a dollar sign somewhere in the variable's value)
   1896      * we just call Var_Subst to do any other substitutions that are
   1897      * necessary. Note that the value returned by Var_Subst will have
   1898      * been dynamically-allocated, so it will need freeing when we
   1899      * return.
   1900      */
   1901     str = (char *)Buf_GetAll(v->val, (int *)NULL);
   1902     if (strchr (str, '$') != (char *)NULL) {
   1903 	str = Var_Subst(NULL, str, ctxt, err);
   1904 	*freePtr = TRUE;
   1905     }
   1906 
   1907     v->flags &= ~VAR_IN_USE;
   1908 
   1909     /*
   1910      * Now we need to apply any modifiers the user wants applied.
   1911      * These are:
   1912      *  	  :M<pattern>	words which match the given <pattern>.
   1913      *  	  	    	<pattern> is of the standard file
   1914      *  	  	    	wildcarding form.
   1915      *  	  :N<pattern>	words which do not match the given <pattern>.
   1916      *  	  :S<d><pat1><d><pat2><d>[g]
   1917      *  	  	    	Substitute <pat2> for <pat1> in the value
   1918      *  	  :C<d><pat1><d><pat2><d>[g]
   1919      *  	  	    	Substitute <pat2> for regex <pat1> in the value
   1920      *  	  :H	    	Substitute the head of each word
   1921      *  	  :T	    	Substitute the tail of each word
   1922      *  	  :E	    	Substitute the extension (minus '.') of
   1923      *  	  	    	each word
   1924      *  	  :R	    	Substitute the root of each word
   1925      *  	  	    	(pathname minus the suffix).
   1926      *		  :O		("Order") Sort words in variable.
   1927      *		  :u		("uniq") Remove adjacent duplicate words.
   1928      *		  :?<true-value>:<false-value>
   1929      *				If the variable evaluates to true, return
   1930      *				true value, else return the second value.
   1931      *	    	  :lhs=rhs  	Like :S, but the rhs goes to the end of
   1932      *	    	    	    	the invocation.
   1933      *		  :sh		Treat the current value as a command
   1934      *				to be run, new value is its output.
   1935      * The following added so we can handle ODE makefiles.
   1936      *		  :@<tmpvar>@<newval>@
   1937      *				Assign a temporary local variable <tmpvar>
   1938      *				to the current value of each word in turn
   1939      *				and replace each word with the result of
   1940      *				evaluating <newval>
   1941      *		  :D<newval>	Use <newval> as value if variable defined
   1942      *		  :U<newval>	Use <newval> as value if variable undefined
   1943      *		  :L		Use the name of the variable as the value.
   1944      *		  :P		Use the path of the node that has the same
   1945      *				name as the variable as the value.  This
   1946      *				basically includes an implied :L so that
   1947      *				the common method of refering to the path
   1948      *				of your dependent 'x' in a rule is to use
   1949      *				the form '${x:P}'.
   1950      *		  :!<cmd>!	Run cmd much the same as :sh run's the
   1951      *				current value of the variable.
   1952      * The ::= modifiers, actually assign a value to the variable.
   1953      * Their main purpose is in supporting modifiers of .for loop
   1954      * iterators and other obscure uses.  They always expand to
   1955      * nothing.  In a target rule that would otherwise expand to an
   1956      * empty line they can be preceded with @: to keep make happy.
   1957      * Eg.
   1958      *
   1959      * foo:	.USE
   1960      * .for i in ${.TARGET} ${.TARGET:R}.gz
   1961      * 		@: ${t::=$i}
   1962      *		@echo blah ${t:T}
   1963      * .endfor
   1964      *
   1965      *		  ::=<str>	Assigns <str> as the new value of variable.
   1966      *		  ::?=<str>	Assigns <str> as value of variable if
   1967      *				it was not already set.
   1968      *		  ::+=<str>	Appends <str> to variable.
   1969      *		  ::!=<cmd>	Assigns output of <cmd> as the new value of
   1970      *				variable.
   1971      */
   1972     if ((str != (char *)NULL) && haveModifier) {
   1973 	/*
   1974 	 * Skip initial colon while putting it back.
   1975 	 */
   1976 	*tstr++ = ':';
   1977 	while (*tstr != endc) {
   1978 	    char	*newStr;    /* New value to return */
   1979 	    char	termc;	    /* Character which terminated scan */
   1980 
   1981 	    if (DEBUG(VAR)) {
   1982 		printf("Applying :%c to \"%s\"\n", *tstr, str);
   1983 	    }
   1984 	    switch (*tstr) {
   1985 	        case ':':
   1986 
   1987 		if (tstr[1] == '=' ||
   1988 		    (tstr[2] == '=' &&
   1989 		     (tstr[1] == '!' || tstr[1] == '+' || tstr[1] == '?'))) {
   1990 		    GNode *v_ctxt;		/* context where v belongs */
   1991 		    char *emsg;
   1992 		    VarPattern	pattern;
   1993 		    int	how;
   1994 
   1995 		    ++tstr;
   1996 		    if (v->flags & VAR_JUNK) {
   1997 			/*
   1998 			 * We need to strdup() it incase
   1999 			 * VarGetPattern() recurses.
   2000 			 */
   2001 			v->name = strdup(v->name);
   2002 			v_ctxt = ctxt;
   2003 		    } else if (ctxt != VAR_GLOBAL) {
   2004 			if (VarFind(v->name, ctxt, 0) == (Var *)NIL)
   2005 			    v_ctxt = VAR_GLOBAL;
   2006 			else
   2007 			    v_ctxt = ctxt;
   2008 		    }
   2009 
   2010 		    switch ((how = *tstr)) {
   2011 		    case '+':
   2012 		    case '?':
   2013 		    case '!':
   2014 			cp = &tstr[2];
   2015 			break;
   2016 		    default:
   2017 			cp = ++tstr;
   2018 			break;
   2019 		    }
   2020 		    delim = '}';
   2021 		    pattern.flags = 0;
   2022 
   2023 		    if ((pattern.rhs = VarGetPattern(ctxt, err, &cp, delim,
   2024 						     NULL, &pattern.rightLen, NULL)) == NULL) {
   2025 			if (v->flags & VAR_JUNK) {
   2026 			    free(v->name);
   2027 			    v->name = str;
   2028 			}
   2029 			goto cleanup;
   2030 		    }
   2031 		    termc = *--cp;
   2032 		    delim = '\0';
   2033 
   2034 		    switch (how) {
   2035 		    case '+':
   2036 			Var_Append(v->name, pattern.rhs, v_ctxt);
   2037 			break;
   2038 		    case '!':
   2039 			newStr = Cmd_Exec (pattern.rhs, &emsg);
   2040 			if (emsg)
   2041 			    Error (emsg, str);
   2042 			else
   2043 			   Var_Set(v->name, newStr,  v_ctxt);
   2044 			if (newStr)
   2045 			    free(newStr);
   2046 			break;
   2047 		    case '?':
   2048 			if ((v->flags & VAR_JUNK) == 0)
   2049 			    break;
   2050 			/* FALLTHROUGH */
   2051 		    default:
   2052 			Var_Set(v->name, pattern.rhs, v_ctxt);
   2053 			break;
   2054 		    }
   2055 		    if (v->flags & VAR_JUNK) {
   2056 			free(v->name);
   2057 			v->name = str;
   2058 		    }
   2059 		    free(pattern.rhs);
   2060 		    newStr = var_Error;
   2061 		    break;
   2062 		}
   2063 		goto default_case;
   2064 	        case '@':
   2065 		{
   2066 		    VarLoop_t	loop;
   2067 		    int flags = VAR_NOSUBST;
   2068 
   2069 		    cp = ++tstr;
   2070 		    delim = '@';
   2071 		    if ((loop.tvar = VarGetPattern(ctxt, err, &cp, delim,
   2072 						   &flags, &loop.tvarLen,
   2073 						   NULL)) == NULL)
   2074 			goto cleanup;
   2075 
   2076 		    if ((loop.str = VarGetPattern(ctxt, err, &cp, delim,
   2077 						  &flags, &loop.strLen,
   2078 						  NULL)) == NULL)
   2079 			goto cleanup;
   2080 
   2081 		    termc = *cp;
   2082 		    delim = '\0';
   2083 
   2084 		    loop.err = err;
   2085 		    loop.ctxt = ctxt;
   2086 		    newStr = VarModify(ctxt, str, VarLoopExpand,
   2087 				       (ClientData)&loop);
   2088 		    free(loop.tvar);
   2089 		    free(loop.str);
   2090 		    break;
   2091 		}
   2092 	        case 'D':
   2093 	        case 'U':
   2094 		{
   2095 		    Buffer  buf;    	/* Buffer for patterns */
   2096 		    int	    wantit;	/* want data in buffer */
   2097 
   2098 		    /*
   2099 		     * Pass through tstr looking for 1) escaped delimiters,
   2100 		     * '$'s and backslashes (place the escaped character in
   2101 		     * uninterpreted) and 2) unescaped $'s that aren't before
   2102 		     * the delimiter (expand the variable substitution).
   2103 		     * The result is left in the Buffer buf.
   2104 		     */
   2105 		    buf = Buf_Init(0);
   2106 		    for (cp = tstr + 1;
   2107 			 *cp != endc && *cp != ':' && *cp != '\0';
   2108 			 cp++) {
   2109 			if ((*cp == '\\') &&
   2110 			    ((cp[1] == ':') ||
   2111 			     (cp[1] == '$') ||
   2112 			     (cp[1] == endc) ||
   2113 			     (cp[1] == '\\')))
   2114 			{
   2115 			    Buf_AddByte(buf, (Byte) cp[1]);
   2116 			    cp++;
   2117 			} else if (*cp == '$') {
   2118 			    /*
   2119 			     * If unescaped dollar sign, assume it's a
   2120 			     * variable substitution and recurse.
   2121 			     */
   2122 			    char    *cp2;
   2123 			    int	    len;
   2124 			    Boolean freeIt;
   2125 
   2126 			    cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
   2127 			    Buf_AddBytes(buf, strlen(cp2), (Byte *) cp2);
   2128 			    if (freeIt)
   2129 				free(cp2);
   2130 			    cp += len - 1;
   2131 			} else {
   2132 			    Buf_AddByte(buf, (Byte) *cp);
   2133 			}
   2134 		    }
   2135 		    Buf_AddByte(buf, (Byte) '\0');
   2136 
   2137 		    termc = *cp;
   2138 
   2139 		    if (*tstr == 'U')
   2140 			wantit = ((v->flags & VAR_JUNK) != 0);
   2141 		    else
   2142 			wantit = ((v->flags & VAR_JUNK) == 0);
   2143 		    if ((v->flags & VAR_JUNK) != 0)
   2144 			v->flags |= VAR_KEEP;
   2145 		    if (wantit) {
   2146 			newStr = (char *)Buf_GetAll(buf, (int *)NULL);
   2147 			Buf_Destroy(buf, FALSE);
   2148 		    } else {
   2149 			newStr = str;
   2150 			Buf_Destroy(buf, TRUE);
   2151 		    }
   2152 		    break;
   2153 		}
   2154 	        case 'L':
   2155 		{
   2156 		    if ((v->flags & VAR_JUNK) != 0)
   2157 			v->flags |= VAR_KEEP;
   2158 		    newStr = strdup(v->name);
   2159 		    cp = ++tstr;
   2160 		    termc = *tstr;
   2161 		    break;
   2162 		}
   2163 	        case 'P':
   2164 		{
   2165 		    GNode *gn;
   2166 
   2167 		    if ((v->flags & VAR_JUNK) != 0)
   2168 			v->flags |= VAR_KEEP;
   2169 		    gn = Targ_FindNode(v->name, TARG_NOCREATE);
   2170 		    if (gn == NILGNODE || gn->path == NULL)
   2171 			newStr = strdup(v->name);
   2172 		    else
   2173 			newStr = strdup(gn->path);
   2174 		    cp = ++tstr;
   2175 		    termc = *tstr;
   2176 		    break;
   2177 		}
   2178 	        case '!':
   2179 		{
   2180 		    char *emsg;
   2181 		    VarPattern 	    pattern;
   2182 		    pattern.flags = 0;
   2183 
   2184 		    delim = '!';
   2185 
   2186 		    cp = ++tstr;
   2187 		    if ((pattern.rhs = VarGetPattern(ctxt, err, &cp, delim,
   2188 						     NULL, &pattern.rightLen, NULL)) == NULL)
   2189 			goto cleanup;
   2190 		    newStr = Cmd_Exec (pattern.rhs, &emsg);
   2191 		    free(pattern.rhs);
   2192 		    if (emsg)
   2193 			Error (emsg, str);
   2194 		    termc = *cp;
   2195 		    delim = '\0';
   2196 		    if (v->flags & VAR_JUNK) {
   2197 			v->flags |= VAR_KEEP;
   2198 		    }
   2199 		    break;
   2200 		}
   2201 		case 'N':
   2202 		case 'M':
   2203 		{
   2204 		    char    *pattern;
   2205 		    char    *cp2;
   2206 		    Boolean copy;
   2207 		    int nest;
   2208 
   2209 		    copy = FALSE;
   2210 		    nest = 1;
   2211 		    for (cp = tstr + 1;
   2212 			 *cp != '\0' && *cp != ':';
   2213 			 cp++)
   2214 		    {
   2215 			if (*cp == '\\' &&
   2216 			    (cp[1] == ':' ||
   2217 			     cp[1] == endc || cp[1] == startc)) {
   2218 			    copy = TRUE;
   2219 			    cp++;
   2220 			    continue;
   2221 			}
   2222 			if (*cp == startc)
   2223 			    ++nest;
   2224 			if (*cp == endc) {
   2225 			    --nest;
   2226 			    if (nest == 0)
   2227 				break;
   2228 			}
   2229 		    }
   2230 		    termc = *cp;
   2231 		    *cp = '\0';
   2232 		    if (copy) {
   2233 			/*
   2234 			 * Need to compress the \:'s out of the pattern, so
   2235 			 * allocate enough room to hold the uncompressed
   2236 			 * pattern (note that cp started at tstr+1, so
   2237 			 * cp - tstr takes the null byte into account) and
   2238 			 * compress the pattern into the space.
   2239 			 */
   2240 			pattern = emalloc(cp - tstr);
   2241 			for (cp2 = pattern, cp = tstr + 1;
   2242 			     *cp != '\0';
   2243 			     cp++, cp2++)
   2244 			{
   2245 			    if ((*cp == '\\') &&
   2246 				(cp[1] == ':' || cp[1] == endc)) {
   2247 				    cp++;
   2248 			    }
   2249 			    *cp2 = *cp;
   2250 			}
   2251 			*cp2 = '\0';
   2252 		    } else {
   2253 			pattern = &tstr[1];
   2254 		    }
   2255 		    if ((cp2 = strchr(pattern, '$'))) {
   2256 			cp2 = pattern;
   2257 			pattern = Var_Subst(NULL, cp2, ctxt, err);
   2258 			if (copy)
   2259 			    free(cp2);
   2260 			copy = TRUE;
   2261 		    }
   2262 		    if (*tstr == 'M' || *tstr == 'm') {
   2263 			newStr = VarModify(ctxt, str, VarMatch, (ClientData)pattern);
   2264 		    } else {
   2265 			newStr = VarModify(ctxt, str, VarNoMatch,
   2266 					   (ClientData)pattern);
   2267 		    }
   2268 		    if (copy) {
   2269 			free(pattern);
   2270 		    }
   2271 		    break;
   2272 		}
   2273 		case 'S':
   2274 		{
   2275 		    VarPattern 	    pattern;
   2276 
   2277 		    pattern.flags = 0;
   2278 		    delim = tstr[1];
   2279 		    tstr += 2;
   2280 
   2281 		    /*
   2282 		     * If pattern begins with '^', it is anchored to the
   2283 		     * start of the word -- skip over it and flag pattern.
   2284 		     */
   2285 		    if (*tstr == '^') {
   2286 			pattern.flags |= VAR_MATCH_START;
   2287 			tstr += 1;
   2288 		    }
   2289 
   2290 		    cp = tstr;
   2291 		    if ((pattern.lhs = VarGetPattern(ctxt, err, &cp, delim,
   2292 			&pattern.flags, &pattern.leftLen, NULL)) == NULL)
   2293 			goto cleanup;
   2294 
   2295 		    if ((pattern.rhs = VarGetPattern(ctxt, err, &cp, delim,
   2296 			NULL, &pattern.rightLen, &pattern)) == NULL)
   2297 			goto cleanup;
   2298 
   2299 		    /*
   2300 		     * Check for global substitution. If 'g' after the final
   2301 		     * delimiter, substitution is global and is marked that
   2302 		     * way.
   2303 		     */
   2304 		    for (;; cp++) {
   2305 			switch (*cp) {
   2306 			case 'g':
   2307 			    pattern.flags |= VAR_SUB_GLOBAL;
   2308 			    continue;
   2309 			case '1':
   2310 			    pattern.flags |= VAR_SUB_ONE;
   2311 			    continue;
   2312 			}
   2313 			break;
   2314 		    }
   2315 
   2316 		    termc = *cp;
   2317 		    newStr = VarModify(ctxt, str, VarSubstitute,
   2318 				       (ClientData)&pattern);
   2319 
   2320 		    /*
   2321 		     * Free the two strings.
   2322 		     */
   2323 		    free(pattern.lhs);
   2324 		    free(pattern.rhs);
   2325 		    break;
   2326 		}
   2327 		case '?':
   2328 		{
   2329 		    VarPattern 	pattern;
   2330 		    Boolean	value;
   2331 
   2332 		    /* find ':', and then substitute accordingly */
   2333 
   2334 		    pattern.flags = 0;
   2335 
   2336 		    cp = ++tstr;
   2337 		    delim = ':';
   2338 		    if ((pattern.lhs = VarGetPattern(ctxt, err, &cp, delim,
   2339 			NULL, &pattern.leftLen, NULL)) == NULL)
   2340 			goto cleanup;
   2341 
   2342 		    delim = '}';
   2343 		    if ((pattern.rhs = VarGetPattern(ctxt, err, &cp, delim,
   2344 			NULL, &pattern.rightLen, NULL)) == NULL)
   2345 			goto cleanup;
   2346 
   2347 		    termc = *--cp;
   2348 		    delim = '\0';
   2349 		    if (Cond_EvalExpression(1, str, &value, 0) == COND_INVALID){
   2350 			Error("Bad conditional expression `%s' in %s?%s:%s",
   2351 			      str, str, pattern.lhs, pattern.rhs);
   2352 			goto cleanup;
   2353 		    }
   2354 
   2355 		    if (value) {
   2356 			newStr = pattern.lhs;
   2357 			free(pattern.rhs);
   2358 		    } else {
   2359 			newStr = pattern.rhs;
   2360 			free(pattern.lhs);
   2361 		    }
   2362 		    break;
   2363 		}
   2364 #ifndef NO_REGEX
   2365 		case 'C':
   2366 		{
   2367 		    VarREPattern    pattern;
   2368 		    char           *re;
   2369 		    int             error;
   2370 
   2371 		    pattern.flags = 0;
   2372 		    delim = tstr[1];
   2373 		    tstr += 2;
   2374 
   2375 		    cp = tstr;
   2376 
   2377 		    if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
   2378 			NULL, NULL)) == NULL)
   2379 			goto cleanup;
   2380 
   2381 		    if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
   2382 			delim, NULL, NULL, NULL)) == NULL){
   2383 			free(re);
   2384 			goto cleanup;
   2385 		    }
   2386 
   2387 		    for (;; cp++) {
   2388 			switch (*cp) {
   2389 			case 'g':
   2390 			    pattern.flags |= VAR_SUB_GLOBAL;
   2391 			    continue;
   2392 			case '1':
   2393 			    pattern.flags |= VAR_SUB_ONE;
   2394 			    continue;
   2395 			}
   2396 			break;
   2397 		    }
   2398 
   2399 		    termc = *cp;
   2400 
   2401 		    error = regcomp(&pattern.re, re, REG_EXTENDED);
   2402 		    free(re);
   2403 		    if (error)  {
   2404 			*lengthPtr = cp - start + 1;
   2405 			VarREError(error, &pattern.re, "RE substitution error");
   2406 			free(pattern.replace);
   2407 			return (var_Error);
   2408 		    }
   2409 
   2410 		    pattern.nsub = pattern.re.re_nsub + 1;
   2411 		    if (pattern.nsub < 1)
   2412 			pattern.nsub = 1;
   2413 		    if (pattern.nsub > 10)
   2414 			pattern.nsub = 10;
   2415 		    pattern.matches = emalloc(pattern.nsub *
   2416 					      sizeof(regmatch_t));
   2417 		    newStr = VarModify(ctxt, str, VarRESubstitute,
   2418 				       (ClientData) &pattern);
   2419 		    regfree(&pattern.re);
   2420 		    free(pattern.replace);
   2421 		    free(pattern.matches);
   2422 		    break;
   2423 		}
   2424 #endif
   2425 		case 'Q':
   2426 		    if (tstr[1] == endc || tstr[1] == ':') {
   2427 			newStr = VarQuote (str);
   2428 			cp = tstr + 1;
   2429 			termc = *cp;
   2430 			break;
   2431 		    }
   2432 		    /*FALLTHRU*/
   2433 		case 'T':
   2434 		    if (tstr[1] == endc || tstr[1] == ':') {
   2435 			newStr = VarModify(ctxt, str, VarTail, (ClientData)0);
   2436 			cp = tstr + 1;
   2437 			termc = *cp;
   2438 			break;
   2439 		    }
   2440 		    /*FALLTHRU*/
   2441 		case 'H':
   2442 		    if (tstr[1] == endc || tstr[1] == ':') {
   2443 			newStr = VarModify(ctxt, str, VarHead, (ClientData)0);
   2444 			cp = tstr + 1;
   2445 			termc = *cp;
   2446 			break;
   2447 		    }
   2448 		    /*FALLTHRU*/
   2449 		case 'E':
   2450 		    if (tstr[1] == endc || tstr[1] == ':') {
   2451 			newStr = VarModify(ctxt, str, VarSuffix, (ClientData)0);
   2452 			cp = tstr + 1;
   2453 			termc = *cp;
   2454 			break;
   2455 		    }
   2456 		    /*FALLTHRU*/
   2457 		case 'R':
   2458 		    if (tstr[1] == endc || tstr[1] == ':') {
   2459 			newStr = VarModify(ctxt, str, VarRoot, (ClientData)0);
   2460 			cp = tstr + 1;
   2461 			termc = *cp;
   2462 			break;
   2463 		    }
   2464 		    /*FALLTHRU*/
   2465 		case 'O':
   2466 		    if (tstr[1] == endc || tstr[1] == ':') {
   2467 			newStr = VarSort (str);
   2468 			cp = tstr + 1;
   2469 			termc = *cp;
   2470 			break;
   2471 		    }
   2472 		    /*FALLTHRU*/
   2473 		case 'u':
   2474 		    if (tstr[1] == endc || tstr[1] == ':') {
   2475 			newStr = VarUniq (str);
   2476 			cp = tstr + 1;
   2477 			termc = *cp;
   2478 			break;
   2479 		    }
   2480 		    /*FALLTHRU*/
   2481 #ifdef SUNSHCMD
   2482 		case 's':
   2483 		    if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
   2484 			char *err;
   2485 			newStr = Cmd_Exec (str, &err);
   2486 			if (err)
   2487 			    Error (err, str);
   2488 			cp = tstr + 2;
   2489 			termc = *cp;
   2490 			break;
   2491 		    }
   2492 		    /*FALLTHRU*/
   2493 #endif
   2494                 default:
   2495 		default_case:
   2496 		{
   2497 #ifdef SYSVVARSUB
   2498 		    /*
   2499 		     * This can either be a bogus modifier or a System-V
   2500 		     * substitution command.
   2501 		     */
   2502 		    VarPattern      pattern;
   2503 		    Boolean         eqFound;
   2504 
   2505 		    pattern.flags = 0;
   2506 		    eqFound = FALSE;
   2507 		    /*
   2508 		     * First we make a pass through the string trying
   2509 		     * to verify it is a SYSV-make-style translation:
   2510 		     * it must be: <string1>=<string2>)
   2511 		     */
   2512 		    cp = tstr;
   2513 		    cnt = 1;
   2514 		    while (*cp != '\0' && cnt) {
   2515 			if (*cp == '=') {
   2516 			    eqFound = TRUE;
   2517 			    /* continue looking for endc */
   2518 			}
   2519 			else if (*cp == endc)
   2520 			    cnt--;
   2521 			else if (*cp == startc)
   2522 			    cnt++;
   2523 			if (cnt)
   2524 			    cp++;
   2525 		    }
   2526 		    if (*cp == endc && eqFound) {
   2527 
   2528 			/*
   2529 			 * Now we break this sucker into the lhs and
   2530 			 * rhs. We must null terminate them of course.
   2531 			 */
   2532 			for (cp = tstr; *cp != '='; cp++)
   2533 			    continue;
   2534 			pattern.lhs = tstr;
   2535 			pattern.leftLen = cp - tstr;
   2536 			*cp++ = '\0';
   2537 
   2538 			pattern.rhs = cp;
   2539 			cnt = 1;
   2540 			while (cnt) {
   2541 			    if (*cp == endc)
   2542 				cnt--;
   2543 			    else if (*cp == startc)
   2544 				cnt++;
   2545 			    if (cnt)
   2546 				cp++;
   2547 			}
   2548 			pattern.rightLen = cp - pattern.rhs;
   2549 			*cp = '\0';
   2550 
   2551 			/*
   2552 			 * SYSV modifications happen through the whole
   2553 			 * string. Note the pattern is anchored at the end.
   2554 			 */
   2555 			newStr = VarModify(ctxt, str, VarSYSVMatch,
   2556 					   (ClientData)&pattern);
   2557 
   2558 			/*
   2559 			 * Restore the nulled characters
   2560 			 */
   2561 			pattern.lhs[pattern.leftLen] = '=';
   2562 			pattern.rhs[pattern.rightLen] = endc;
   2563 			termc = endc;
   2564 		    } else
   2565 #endif
   2566 		    {
   2567 			Error ("Unknown modifier '%c'\n", *tstr);
   2568 			for (cp = tstr+1;
   2569 			     *cp != ':' && *cp != endc && *cp != '\0';
   2570 			     cp++)
   2571 				 continue;
   2572 			termc = *cp;
   2573 			newStr = var_Error;
   2574 		    }
   2575 		}
   2576 	    }
   2577 	    if (DEBUG(VAR)) {
   2578 		printf("Result is \"%s\"\n", newStr);
   2579 	    }
   2580 
   2581 	    if (newStr != str) {
   2582 		if (*freePtr) {
   2583 		    free (str);
   2584 		}
   2585 		str = newStr;
   2586 		if (str != var_Error && str != varNoError) {
   2587 		    *freePtr = TRUE;
   2588 		} else {
   2589 		    *freePtr = FALSE;
   2590 		}
   2591 	    }
   2592 	    if (termc == '\0') {
   2593 		Error("Unclosed variable specification for %s", v->name);
   2594 	    } else if (termc == ':') {
   2595 		*cp++ = termc;
   2596 	    } else {
   2597 		*cp = termc;
   2598 	    }
   2599 	    tstr = cp;
   2600 	}
   2601 	*lengthPtr = tstr - start + 1;
   2602     } else {
   2603 	*lengthPtr = tstr - start + 1;
   2604 	*tstr = endc;
   2605     }
   2606 
   2607     if (v->flags & VAR_FROM_ENV) {
   2608 	Boolean	  destroy = FALSE;
   2609 
   2610 	if (str != (char *)Buf_GetAll(v->val, (int *)NULL)) {
   2611 	    destroy = TRUE;
   2612 	} else {
   2613 	    /*
   2614 	     * Returning the value unmodified, so tell the caller to free
   2615 	     * the thing.
   2616 	     */
   2617 	    *freePtr = TRUE;
   2618 	}
   2619 	if (str != (char *)Buf_GetAll(v->val, (int *)NULL))
   2620 	    Buf_Destroy(v->val, destroy);
   2621 	free((Address)v->name);
   2622 	free((Address)v);
   2623     } else if (v->flags & VAR_JUNK) {
   2624 	/*
   2625 	 * Perform any free'ing needed and set *freePtr to FALSE so the caller
   2626 	 * doesn't try to free a static pointer.
   2627 	 * If VAR_KEEP is also set then we want to keep str as is.
   2628 	 */
   2629 	if (!(v->flags & VAR_KEEP)) {
   2630 	    if (*freePtr) {
   2631 		free(str);
   2632 	    }
   2633 	    *freePtr = FALSE;
   2634 	    if (dynamic) {
   2635 		str = emalloc(*lengthPtr + 1);
   2636 		strncpy(str, start, *lengthPtr);
   2637 		str[*lengthPtr] = '\0';
   2638 		*freePtr = TRUE;
   2639 	    } else {
   2640 		str = var_Error;
   2641 	    }
   2642 	}
   2643 	if (str != (char *)Buf_GetAll(v->val, (int *)NULL))
   2644 	    Buf_Destroy(v->val, TRUE);
   2645 	free((Address)v->name);
   2646 	free((Address)v);
   2647     }
   2648     return (str);
   2649 
   2650 cleanup:
   2651     *lengthPtr = cp - start + 1;
   2652     if (*freePtr)
   2653 	free(str);
   2654     if (delim != '\0')
   2655 	Error("Unclosed substitution for %s (%c missing)",
   2656 	      v->name, delim);
   2657     return (var_Error);
   2658 }
   2659 
   2660 /*-
   2661  *-----------------------------------------------------------------------
   2662  * Var_Subst  --
   2663  *	Substitute for all variables in the given string in the given context
   2664  *	If undefErr is TRUE, Parse_Error will be called when an undefined
   2665  *	variable is encountered.
   2666  *
   2667  * Results:
   2668  *	The resulting string.
   2669  *
   2670  * Side Effects:
   2671  *	None. The old string must be freed by the caller
   2672  *-----------------------------------------------------------------------
   2673  */
   2674 char *
   2675 Var_Subst (var, str, ctxt, undefErr)
   2676     char	  *var;		    /* Named variable || NULL for all */
   2677     char 	  *str;	    	    /* the string in which to substitute */
   2678     GNode         *ctxt;	    /* the context wherein to find variables */
   2679     Boolean 	  undefErr; 	    /* TRUE if undefineds are an error */
   2680 {
   2681     Buffer  	  buf;	    	    /* Buffer for forming things */
   2682     char    	  *val;		    /* Value to substitute for a variable */
   2683     int	    	  length;   	    /* Length of the variable invocation */
   2684     Boolean 	  doFree;   	    /* Set true if val should be freed */
   2685     static Boolean errorReported;   /* Set true if an error has already
   2686 				     * been reported to prevent a plethora
   2687 				     * of messages when recursing */
   2688 
   2689     buf = Buf_Init (MAKE_BSIZE);
   2690     errorReported = FALSE;
   2691 
   2692     while (*str) {
   2693 	if (var == NULL && (*str == '$') && (str[1] == '$')) {
   2694 	    /*
   2695 	     * A dollar sign may be escaped either with another dollar sign.
   2696 	     * In such a case, we skip over the escape character and store the
   2697 	     * dollar sign into the buffer directly.
   2698 	     */
   2699 	    str++;
   2700 	    Buf_AddByte(buf, (Byte)*str);
   2701 	    str++;
   2702 	} else if (*str != '$') {
   2703 	    /*
   2704 	     * Skip as many characters as possible -- either to the end of
   2705 	     * the string or to the next dollar sign (variable invocation).
   2706 	     */
   2707 	    char  *cp;
   2708 
   2709 	    for (cp = str++; *str != '$' && *str != '\0'; str++)
   2710 		continue;
   2711 	    Buf_AddBytes(buf, str - cp, (Byte *)cp);
   2712 	} else {
   2713 	    if (var != NULL) {
   2714 		int expand;
   2715 		for (;;) {
   2716 		    if (str[1] != '(' && str[1] != '{') {
   2717 			if (str[1] != *var || strlen(var) > 1) {
   2718 			    Buf_AddBytes(buf, 2, (Byte *) str);
   2719 			    str += 2;
   2720 			    expand = FALSE;
   2721 			}
   2722 			else
   2723 			    expand = TRUE;
   2724 			break;
   2725 		    }
   2726 		    else {
   2727 			char *p;
   2728 
   2729 			/*
   2730 			 * Scan up to the end of the variable name.
   2731 			 */
   2732 			for (p = &str[2]; *p &&
   2733 			     *p != ':' && *p != ')' && *p != '}'; p++)
   2734 			    if (*p == '$')
   2735 				break;
   2736 			/*
   2737 			 * A variable inside the variable. We cannot expand
   2738 			 * the external variable yet, so we try again with
   2739 			 * the nested one
   2740 			 */
   2741 			if (*p == '$') {
   2742 			    Buf_AddBytes(buf, p - str, (Byte *) str);
   2743 			    str = p;
   2744 			    continue;
   2745 			}
   2746 
   2747 			if (strncmp(var, str + 2, p - str - 2) != 0 ||
   2748 			    var[p - str - 2] != '\0') {
   2749 			    /*
   2750 			     * Not the variable we want to expand, scan
   2751 			     * until the next variable
   2752 			     */
   2753 			    for (;*p != '$' && *p != '\0'; p++)
   2754 				continue;
   2755 			    Buf_AddBytes(buf, p - str, (Byte *) str);
   2756 			    str = p;
   2757 			    expand = FALSE;
   2758 			}
   2759 			else
   2760 			    expand = TRUE;
   2761 			break;
   2762 		    }
   2763 		}
   2764 		if (!expand)
   2765 		    continue;
   2766 	    }
   2767 
   2768 	    val = Var_Parse (str, ctxt, undefErr, &length, &doFree);
   2769 
   2770 	    /*
   2771 	     * When we come down here, val should either point to the
   2772 	     * value of this variable, suitably modified, or be NULL.
   2773 	     * Length should be the total length of the potential
   2774 	     * variable invocation (from $ to end character...)
   2775 	     */
   2776 	    if (val == var_Error || val == varNoError) {
   2777 		/*
   2778 		 * If performing old-time variable substitution, skip over
   2779 		 * the variable and continue with the substitution. Otherwise,
   2780 		 * store the dollar sign and advance str so we continue with
   2781 		 * the string...
   2782 		 */
   2783 		if (oldVars) {
   2784 		    str += length;
   2785 		} else if (undefErr) {
   2786 		    /*
   2787 		     * If variable is undefined, complain and skip the
   2788 		     * variable. The complaint will stop us from doing anything
   2789 		     * when the file is parsed.
   2790 		     */
   2791 		    if (!errorReported) {
   2792 			Parse_Error (PARSE_FATAL,
   2793 				     "Undefined variable \"%.*s\"",length,str);
   2794 		    }
   2795 		    str += length;
   2796 		    errorReported = TRUE;
   2797 		} else {
   2798 		    Buf_AddByte (buf, (Byte)*str);
   2799 		    str += 1;
   2800 		}
   2801 	    } else {
   2802 		/*
   2803 		 * We've now got a variable structure to store in. But first,
   2804 		 * advance the string pointer.
   2805 		 */
   2806 		str += length;
   2807 
   2808 		/*
   2809 		 * Copy all the characters from the variable value straight
   2810 		 * into the new string.
   2811 		 */
   2812 		Buf_AddBytes (buf, strlen (val), (Byte *)val);
   2813 		if (doFree) {
   2814 		    free ((Address)val);
   2815 		}
   2816 	    }
   2817 	}
   2818     }
   2819 
   2820     Buf_AddByte (buf, '\0');
   2821     str = (char *)Buf_GetAll (buf, (int *)NULL);
   2822     Buf_Destroy (buf, FALSE);
   2823     return (str);
   2824 }
   2825 
   2826 /*-
   2827  *-----------------------------------------------------------------------
   2828  * Var_GetTail --
   2829  *	Return the tail from each of a list of words. Used to set the
   2830  *	System V local variables.
   2831  *
   2832  * Results:
   2833  *	The resulting string.
   2834  *
   2835  * Side Effects:
   2836  *	None.
   2837  *
   2838  *-----------------------------------------------------------------------
   2839  */
   2840 #if 0
   2841 char *
   2842 Var_GetTail(file)
   2843     char    	*file;	    /* Filename to modify */
   2844 {
   2845     return(VarModify(file, VarTail, (ClientData)0));
   2846 }
   2847 
   2848 /*-
   2849  *-----------------------------------------------------------------------
   2850  * Var_GetHead --
   2851  *	Find the leading components of a (list of) filename(s).
   2852  *	XXX: VarHead does not replace foo by ., as (sun) System V make
   2853  *	does.
   2854  *
   2855  * Results:
   2856  *	The leading components.
   2857  *
   2858  * Side Effects:
   2859  *	None.
   2860  *
   2861  *-----------------------------------------------------------------------
   2862  */
   2863 char *
   2864 Var_GetHead(file)
   2865     char    	*file;	    /* Filename to manipulate */
   2866 {
   2867     return(VarModify(file, VarHead, (ClientData)0));
   2868 }
   2869 #endif
   2870 
   2871 /*-
   2872  *-----------------------------------------------------------------------
   2873  * Var_Init --
   2874  *	Initialize the module
   2875  *
   2876  * Results:
   2877  *	None
   2878  *
   2879  * Side Effects:
   2880  *	The VAR_CMD and VAR_GLOBAL contexts are created
   2881  *-----------------------------------------------------------------------
   2882  */
   2883 void
   2884 Var_Init ()
   2885 {
   2886     VAR_GLOBAL = Targ_NewGN ("Global");
   2887     VAR_CMD = Targ_NewGN ("Command");
   2888 
   2889 }
   2890 
   2891 
   2892 void
   2893 Var_End ()
   2894 {
   2895 }
   2896 
   2897 
   2898 /****************** PRINT DEBUGGING INFO *****************/
   2899 static void
   2900 VarPrintVar (vp)
   2901     ClientData vp;
   2902 {
   2903     Var    *v = (Var *) vp;
   2904     printf ("%-16s = %s\n", v->name, (char *) Buf_GetAll(v->val, (int *)NULL));
   2905 }
   2906 
   2907 /*-
   2908  *-----------------------------------------------------------------------
   2909  * Var_Dump --
   2910  *	print all variables in a context
   2911  *-----------------------------------------------------------------------
   2912  */
   2913 void
   2914 Var_Dump (ctxt)
   2915     GNode          *ctxt;
   2916 {
   2917     Hash_Search search;
   2918     Hash_Entry *h;
   2919 
   2920     for (h = Hash_EnumFirst(&ctxt->context, &search);
   2921 	 h != NULL;
   2922 	 h = Hash_EnumNext(&search)) {
   2923 	    VarPrintVar(Hash_GetValue(h));
   2924     }
   2925 }
   2926