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