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