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