xref: /netbsd-src/usr.bin/make/var.c (revision b519c70ad771d0a55b3c2277db6b97a05fa6465d)
1 /*	$NetBSD: var.c,v 1.66 2001/12/25 14:50:36 lukem 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.66 2001/12/25 14:50:36 lukem 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.66 2001/12/25 14:50:36 lukem 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 			/* '{' */
2011 		    delim = '}';
2012 		    pattern.flags = 0;
2013 
2014 		    if ((pattern.rhs = VarGetPattern(ctxt, err, &cp, delim,
2015 						     NULL, &pattern.rightLen, NULL)) == NULL) {
2016 			if (v->flags & VAR_JUNK) {
2017 			    free(v->name);
2018 			    v->name = str;
2019 			}
2020 			goto cleanup;
2021 		    }
2022 		    termc = *--cp;
2023 		    delim = '\0';
2024 
2025 		    switch (how) {
2026 		    case '+':
2027 			Var_Append(v->name, pattern.rhs, v_ctxt);
2028 			break;
2029 		    case '!':
2030 			newStr = Cmd_Exec (pattern.rhs, &emsg);
2031 			if (emsg)
2032 			    Error (emsg, str);
2033 			else
2034 			   Var_Set(v->name, newStr,  v_ctxt, 0);
2035 			if (newStr)
2036 			    free(newStr);
2037 			break;
2038 		    case '?':
2039 			if ((v->flags & VAR_JUNK) == 0)
2040 			    break;
2041 			/* FALLTHROUGH */
2042 		    default:
2043 			Var_Set(v->name, pattern.rhs, v_ctxt, 0);
2044 			break;
2045 		    }
2046 		    if (v->flags & VAR_JUNK) {
2047 			free(v->name);
2048 			v->name = str;
2049 		    }
2050 		    free(pattern.rhs);
2051 		    newStr = var_Error;
2052 		    break;
2053 		}
2054 		goto default_case;
2055 	        case '@':
2056 		{
2057 		    VarLoop_t	loop;
2058 		    int flags = VAR_NOSUBST;
2059 
2060 		    cp = ++tstr;
2061 		    delim = '@';
2062 		    if ((loop.tvar = VarGetPattern(ctxt, err, &cp, delim,
2063 						   &flags, &loop.tvarLen,
2064 						   NULL)) == NULL)
2065 			goto cleanup;
2066 
2067 		    if ((loop.str = VarGetPattern(ctxt, err, &cp, delim,
2068 						  &flags, &loop.strLen,
2069 						  NULL)) == NULL)
2070 			goto cleanup;
2071 
2072 		    termc = *cp;
2073 		    delim = '\0';
2074 
2075 		    loop.err = err;
2076 		    loop.ctxt = ctxt;
2077 		    newStr = VarModify(ctxt, str, VarLoopExpand,
2078 				       (ClientData)&loop);
2079 		    free(loop.tvar);
2080 		    free(loop.str);
2081 		    break;
2082 		}
2083 	        case 'D':
2084 	        case 'U':
2085 		{
2086 		    Buffer  buf;    	/* Buffer for patterns */
2087 		    int	    wantit;	/* want data in buffer */
2088 
2089 		    /*
2090 		     * Pass through tstr looking for 1) escaped delimiters,
2091 		     * '$'s and backslashes (place the escaped character in
2092 		     * uninterpreted) and 2) unescaped $'s that aren't before
2093 		     * the delimiter (expand the variable substitution).
2094 		     * The result is left in the Buffer buf.
2095 		     */
2096 		    buf = Buf_Init(0);
2097 		    for (cp = tstr + 1;
2098 			 *cp != endc && *cp != ':' && *cp != '\0';
2099 			 cp++) {
2100 			if ((*cp == '\\') &&
2101 			    ((cp[1] == ':') ||
2102 			     (cp[1] == '$') ||
2103 			     (cp[1] == endc) ||
2104 			     (cp[1] == '\\')))
2105 			{
2106 			    Buf_AddByte(buf, (Byte) cp[1]);
2107 			    cp++;
2108 			} else if (*cp == '$') {
2109 			    /*
2110 			     * If unescaped dollar sign, assume it's a
2111 			     * variable substitution and recurse.
2112 			     */
2113 			    char    *cp2;
2114 			    int	    len;
2115 			    Boolean freeIt;
2116 
2117 			    cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
2118 			    Buf_AddBytes(buf, strlen(cp2), (Byte *) cp2);
2119 			    if (freeIt)
2120 				free(cp2);
2121 			    cp += len - 1;
2122 			} else {
2123 			    Buf_AddByte(buf, (Byte) *cp);
2124 			}
2125 		    }
2126 		    Buf_AddByte(buf, (Byte) '\0');
2127 
2128 		    termc = *cp;
2129 
2130 		    if (*tstr == 'U')
2131 			wantit = ((v->flags & VAR_JUNK) != 0);
2132 		    else
2133 			wantit = ((v->flags & VAR_JUNK) == 0);
2134 		    if ((v->flags & VAR_JUNK) != 0)
2135 			v->flags |= VAR_KEEP;
2136 		    if (wantit) {
2137 			newStr = (char *)Buf_GetAll(buf, (int *)NULL);
2138 			Buf_Destroy(buf, FALSE);
2139 		    } else {
2140 			newStr = str;
2141 			Buf_Destroy(buf, TRUE);
2142 		    }
2143 		    break;
2144 		}
2145 	        case 'L':
2146 		{
2147 		    if ((v->flags & VAR_JUNK) != 0)
2148 			v->flags |= VAR_KEEP;
2149 		    newStr = strdup(v->name);
2150 		    cp = ++tstr;
2151 		    termc = *tstr;
2152 		    break;
2153 		}
2154 	        case 'P':
2155 		{
2156 		    GNode *gn;
2157 
2158 		    if ((v->flags & VAR_JUNK) != 0)
2159 			v->flags |= VAR_KEEP;
2160 		    gn = Targ_FindNode(v->name, TARG_NOCREATE);
2161 		    if (gn == NILGNODE || gn->path == NULL)
2162 			newStr = strdup(v->name);
2163 		    else
2164 			newStr = strdup(gn->path);
2165 		    cp = ++tstr;
2166 		    termc = *tstr;
2167 		    break;
2168 		}
2169 	        case '!':
2170 		{
2171 		    char *emsg;
2172 		    VarPattern 	    pattern;
2173 		    pattern.flags = 0;
2174 
2175 		    delim = '!';
2176 
2177 		    cp = ++tstr;
2178 		    if ((pattern.rhs = VarGetPattern(ctxt, err, &cp, delim,
2179 						     NULL, &pattern.rightLen, NULL)) == NULL)
2180 			goto cleanup;
2181 		    newStr = Cmd_Exec (pattern.rhs, &emsg);
2182 		    free(pattern.rhs);
2183 		    if (emsg)
2184 			Error (emsg, str);
2185 		    termc = *cp;
2186 		    delim = '\0';
2187 		    if (v->flags & VAR_JUNK) {
2188 			v->flags |= VAR_KEEP;
2189 		    }
2190 		    break;
2191 		}
2192 		case 'N':
2193 		case 'M':
2194 		{
2195 		    char    *pattern;
2196 		    char    *cp2;
2197 		    Boolean copy;
2198 		    int nest;
2199 
2200 		    copy = FALSE;
2201 		    nest = 1;
2202 		    for (cp = tstr + 1;
2203 			 *cp != '\0' && *cp != ':';
2204 			 cp++)
2205 		    {
2206 			if (*cp == '\\' &&
2207 			    (cp[1] == ':' ||
2208 			     cp[1] == endc || cp[1] == startc)) {
2209 			    copy = TRUE;
2210 			    cp++;
2211 			    continue;
2212 			}
2213 			if (*cp == startc)
2214 			    ++nest;
2215 			if (*cp == endc) {
2216 			    --nest;
2217 			    if (nest == 0)
2218 				break;
2219 			}
2220 		    }
2221 		    termc = *cp;
2222 		    *cp = '\0';
2223 		    if (copy) {
2224 			/*
2225 			 * Need to compress the \:'s out of the pattern, so
2226 			 * allocate enough room to hold the uncompressed
2227 			 * pattern (note that cp started at tstr+1, so
2228 			 * cp - tstr takes the null byte into account) and
2229 			 * compress the pattern into the space.
2230 			 */
2231 			pattern = emalloc(cp - tstr);
2232 			for (cp2 = pattern, cp = tstr + 1;
2233 			     *cp != '\0';
2234 			     cp++, cp2++)
2235 			{
2236 			    if ((*cp == '\\') &&
2237 				(cp[1] == ':' || cp[1] == endc)) {
2238 				    cp++;
2239 			    }
2240 			    *cp2 = *cp;
2241 			}
2242 			*cp2 = '\0';
2243 		    } else {
2244 			pattern = &tstr[1];
2245 		    }
2246 		    if ((cp2 = strchr(pattern, '$'))) {
2247 			cp2 = pattern;
2248 			pattern = Var_Subst(NULL, cp2, ctxt, err);
2249 			if (copy)
2250 			    free(cp2);
2251 			copy = TRUE;
2252 		    }
2253 		    if (*tstr == 'M' || *tstr == 'm') {
2254 			newStr = VarModify(ctxt, str, VarMatch, (ClientData)pattern);
2255 		    } else {
2256 			newStr = VarModify(ctxt, str, VarNoMatch,
2257 					   (ClientData)pattern);
2258 		    }
2259 		    if (copy) {
2260 			free(pattern);
2261 		    }
2262 		    break;
2263 		}
2264 		case 'S':
2265 		{
2266 		    VarPattern 	    pattern;
2267 
2268 		    pattern.flags = 0;
2269 		    delim = tstr[1];
2270 		    tstr += 2;
2271 
2272 		    /*
2273 		     * If pattern begins with '^', it is anchored to the
2274 		     * start of the word -- skip over it and flag pattern.
2275 		     */
2276 		    if (*tstr == '^') {
2277 			pattern.flags |= VAR_MATCH_START;
2278 			tstr += 1;
2279 		    }
2280 
2281 		    cp = tstr;
2282 		    if ((pattern.lhs = VarGetPattern(ctxt, err, &cp, delim,
2283 			&pattern.flags, &pattern.leftLen, NULL)) == NULL)
2284 			goto cleanup;
2285 
2286 		    if ((pattern.rhs = VarGetPattern(ctxt, err, &cp, delim,
2287 			NULL, &pattern.rightLen, &pattern)) == NULL)
2288 			goto cleanup;
2289 
2290 		    /*
2291 		     * Check for global substitution. If 'g' after the final
2292 		     * delimiter, substitution is global and is marked that
2293 		     * way.
2294 		     */
2295 		    for (;; cp++) {
2296 			switch (*cp) {
2297 			case 'g':
2298 			    pattern.flags |= VAR_SUB_GLOBAL;
2299 			    continue;
2300 			case '1':
2301 			    pattern.flags |= VAR_SUB_ONE;
2302 			    continue;
2303 			}
2304 			break;
2305 		    }
2306 
2307 		    termc = *cp;
2308 		    newStr = VarModify(ctxt, str, VarSubstitute,
2309 				       (ClientData)&pattern);
2310 
2311 		    /*
2312 		     * Free the two strings.
2313 		     */
2314 		    free(pattern.lhs);
2315 		    free(pattern.rhs);
2316 		    break;
2317 		}
2318 		case '?':
2319 		{
2320 		    VarPattern 	pattern;
2321 		    Boolean	value;
2322 
2323 		    /* find ':', and then substitute accordingly */
2324 
2325 		    pattern.flags = 0;
2326 
2327 		    cp = ++tstr;
2328 		    delim = ':';
2329 		    if ((pattern.lhs = VarGetPattern(ctxt, err, &cp, delim,
2330 			NULL, &pattern.leftLen, NULL)) == NULL)
2331 			goto cleanup;
2332 
2333 			/* '{' */
2334 		    delim = '}';
2335 		    if ((pattern.rhs = VarGetPattern(ctxt, err, &cp, delim,
2336 			NULL, &pattern.rightLen, NULL)) == NULL)
2337 			goto cleanup;
2338 
2339 		    termc = *--cp;
2340 		    delim = '\0';
2341 		    if (Cond_EvalExpression(1, v->name, &value, 0)
2342 			== COND_INVALID) {
2343 			Error("Bad conditional expression `%s' in %s?%s:%s",
2344 			      v->name, v->name, pattern.lhs, pattern.rhs);
2345 			goto cleanup;
2346 		    }
2347 
2348 		    if (value) {
2349 			newStr = pattern.lhs;
2350 			free(pattern.rhs);
2351 		    } else {
2352 			newStr = pattern.rhs;
2353 			free(pattern.lhs);
2354 		    }
2355 		    break;
2356 		}
2357 #ifndef NO_REGEX
2358 		case 'C':
2359 		{
2360 		    VarREPattern    pattern;
2361 		    char           *re;
2362 		    int             error;
2363 
2364 		    pattern.flags = 0;
2365 		    delim = tstr[1];
2366 		    tstr += 2;
2367 
2368 		    cp = tstr;
2369 
2370 		    if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
2371 			NULL, NULL)) == NULL)
2372 			goto cleanup;
2373 
2374 		    if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
2375 			delim, NULL, NULL, NULL)) == NULL){
2376 			free(re);
2377 			goto cleanup;
2378 		    }
2379 
2380 		    for (;; cp++) {
2381 			switch (*cp) {
2382 			case 'g':
2383 			    pattern.flags |= VAR_SUB_GLOBAL;
2384 			    continue;
2385 			case '1':
2386 			    pattern.flags |= VAR_SUB_ONE;
2387 			    continue;
2388 			}
2389 			break;
2390 		    }
2391 
2392 		    termc = *cp;
2393 
2394 		    error = regcomp(&pattern.re, re, REG_EXTENDED);
2395 		    free(re);
2396 		    if (error)  {
2397 			*lengthPtr = cp - start + 1;
2398 			VarREError(error, &pattern.re, "RE substitution error");
2399 			free(pattern.replace);
2400 			return (var_Error);
2401 		    }
2402 
2403 		    pattern.nsub = pattern.re.re_nsub + 1;
2404 		    if (pattern.nsub < 1)
2405 			pattern.nsub = 1;
2406 		    if (pattern.nsub > 10)
2407 			pattern.nsub = 10;
2408 		    pattern.matches = emalloc(pattern.nsub *
2409 					      sizeof(regmatch_t));
2410 		    newStr = VarModify(ctxt, str, VarRESubstitute,
2411 				       (ClientData) &pattern);
2412 		    regfree(&pattern.re);
2413 		    free(pattern.replace);
2414 		    free(pattern.matches);
2415 		    break;
2416 		}
2417 #endif
2418 		case 'Q':
2419 		    if (tstr[1] == endc || tstr[1] == ':') {
2420 			newStr = VarQuote (str);
2421 			cp = tstr + 1;
2422 			termc = *cp;
2423 			break;
2424 		    }
2425 		    /*FALLTHRU*/
2426 		case 'T':
2427 		    if (tstr[1] == endc || tstr[1] == ':') {
2428 			newStr = VarModify(ctxt, str, VarTail, (ClientData)0);
2429 			cp = tstr + 1;
2430 			termc = *cp;
2431 			break;
2432 		    }
2433 		    /*FALLTHRU*/
2434 		case 'H':
2435 		    if (tstr[1] == endc || tstr[1] == ':') {
2436 			newStr = VarModify(ctxt, str, VarHead, (ClientData)0);
2437 			cp = tstr + 1;
2438 			termc = *cp;
2439 			break;
2440 		    }
2441 		    /*FALLTHRU*/
2442 		case 'E':
2443 		    if (tstr[1] == endc || tstr[1] == ':') {
2444 			newStr = VarModify(ctxt, str, VarSuffix, (ClientData)0);
2445 			cp = tstr + 1;
2446 			termc = *cp;
2447 			break;
2448 		    }
2449 		    /*FALLTHRU*/
2450 		case 'R':
2451 		    if (tstr[1] == endc || tstr[1] == ':') {
2452 			newStr = VarModify(ctxt, str, VarRoot, (ClientData)0);
2453 			cp = tstr + 1;
2454 			termc = *cp;
2455 			break;
2456 		    }
2457 		    /*FALLTHRU*/
2458 		case 'O':
2459 		    if (tstr[1] == endc || tstr[1] == ':') {
2460 			newStr = VarSort (str);
2461 			cp = tstr + 1;
2462 			termc = *cp;
2463 			break;
2464 		    }
2465 		    /*FALLTHRU*/
2466 		case 'u':
2467 		    if (tstr[1] == endc || tstr[1] == ':') {
2468 			newStr = VarUniq (str);
2469 			cp = tstr + 1;
2470 			termc = *cp;
2471 			break;
2472 		    }
2473 		    /*FALLTHRU*/
2474 #ifdef SUNSHCMD
2475 		case 's':
2476 		    if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
2477 			char *err;
2478 			newStr = Cmd_Exec (str, &err);
2479 			if (err)
2480 			    Error (err, str);
2481 			cp = tstr + 2;
2482 			termc = *cp;
2483 			break;
2484 		    }
2485 		    /*FALLTHRU*/
2486 #endif
2487                 default:
2488 		default_case:
2489 		{
2490 #ifdef SYSVVARSUB
2491 		    /*
2492 		     * This can either be a bogus modifier or a System-V
2493 		     * substitution command.
2494 		     */
2495 		    VarPattern      pattern;
2496 		    Boolean         eqFound;
2497 
2498 		    pattern.flags = 0;
2499 		    eqFound = FALSE;
2500 		    /*
2501 		     * First we make a pass through the string trying
2502 		     * to verify it is a SYSV-make-style translation:
2503 		     * it must be: <string1>=<string2>)
2504 		     */
2505 		    cp = tstr;
2506 		    cnt = 1;
2507 		    while (*cp != '\0' && cnt) {
2508 			if (*cp == '=') {
2509 			    eqFound = TRUE;
2510 			    /* continue looking for endc */
2511 			}
2512 			else if (*cp == endc)
2513 			    cnt--;
2514 			else if (*cp == startc)
2515 			    cnt++;
2516 			if (cnt)
2517 			    cp++;
2518 		    }
2519 		    if (*cp == endc && eqFound) {
2520 
2521 			/*
2522 			 * Now we break this sucker into the lhs and
2523 			 * rhs. We must null terminate them of course.
2524 			 */
2525 			for (cp = tstr; *cp != '='; cp++)
2526 			    continue;
2527 			pattern.lhs = tstr;
2528 			pattern.leftLen = cp - tstr;
2529 			*cp++ = '\0';
2530 
2531 			pattern.rhs = cp;
2532 			cnt = 1;
2533 			while (cnt) {
2534 			    if (*cp == endc)
2535 				cnt--;
2536 			    else if (*cp == startc)
2537 				cnt++;
2538 			    if (cnt)
2539 				cp++;
2540 			}
2541 			pattern.rightLen = cp - pattern.rhs;
2542 			*cp = '\0';
2543 
2544 			/*
2545 			 * SYSV modifications happen through the whole
2546 			 * string. Note the pattern is anchored at the end.
2547 			 */
2548 			newStr = VarModify(ctxt, str, VarSYSVMatch,
2549 					   (ClientData)&pattern);
2550 
2551 			/*
2552 			 * Restore the nulled characters
2553 			 */
2554 			pattern.lhs[pattern.leftLen] = '=';
2555 			pattern.rhs[pattern.rightLen] = endc;
2556 			termc = endc;
2557 		    } else
2558 #endif
2559 		    {
2560 			Error ("Unknown modifier '%c'\n", *tstr);
2561 			for (cp = tstr+1;
2562 			     *cp != ':' && *cp != endc && *cp != '\0';
2563 			     cp++)
2564 				 continue;
2565 			termc = *cp;
2566 			newStr = var_Error;
2567 		    }
2568 		}
2569 	    }
2570 	    if (DEBUG(VAR)) {
2571 		printf("Result is \"%s\"\n", newStr);
2572 	    }
2573 
2574 	    if (newStr != str) {
2575 		if (*freePtr) {
2576 		    free (str);
2577 		}
2578 		str = newStr;
2579 		if (str != var_Error && str != varNoError) {
2580 		    *freePtr = TRUE;
2581 		} else {
2582 		    *freePtr = FALSE;
2583 		}
2584 	    }
2585 	    if (termc == '\0') {
2586 		Error("Unclosed variable specification for %s", v->name);
2587 	    } else if (termc == ':') {
2588 		*cp++ = termc;
2589 	    } else {
2590 		*cp = termc;
2591 	    }
2592 	    tstr = cp;
2593 	}
2594 	*lengthPtr = tstr - start + 1;
2595     } else {
2596 	*lengthPtr = tstr - start + 1;
2597 	*tstr = endc;
2598     }
2599 
2600     if (v->flags & VAR_FROM_ENV) {
2601 	Boolean	  destroy = FALSE;
2602 
2603 	if (str != (char *)Buf_GetAll(v->val, (int *)NULL)) {
2604 	    destroy = TRUE;
2605 	} else {
2606 	    /*
2607 	     * Returning the value unmodified, so tell the caller to free
2608 	     * the thing.
2609 	     */
2610 	    *freePtr = TRUE;
2611 	}
2612 	if (str != (char *)Buf_GetAll(v->val, (int *)NULL))
2613 	    Buf_Destroy(v->val, destroy);
2614 	free((Address)v->name);
2615 	free((Address)v);
2616     } else if (v->flags & VAR_JUNK) {
2617 	/*
2618 	 * Perform any free'ing needed and set *freePtr to FALSE so the caller
2619 	 * doesn't try to free a static pointer.
2620 	 * If VAR_KEEP is also set then we want to keep str as is.
2621 	 */
2622 	if (!(v->flags & VAR_KEEP)) {
2623 	    if (*freePtr) {
2624 		free(str);
2625 	    }
2626 	    *freePtr = FALSE;
2627 	    if (dynamic) {
2628 		str = emalloc(*lengthPtr + 1);
2629 		strncpy(str, start, *lengthPtr);
2630 		str[*lengthPtr] = '\0';
2631 		*freePtr = TRUE;
2632 	    } else {
2633 		str = var_Error;
2634 	    }
2635 	}
2636 	if (str != (char *)Buf_GetAll(v->val, (int *)NULL))
2637 	    Buf_Destroy(v->val, TRUE);
2638 	free((Address)v->name);
2639 	free((Address)v);
2640     }
2641     return (str);
2642 
2643 cleanup:
2644     *lengthPtr = cp - start + 1;
2645     if (*freePtr)
2646 	free(str);
2647     if (delim != '\0')
2648 	Error("Unclosed substitution for %s (%c missing)",
2649 	      v->name, delim);
2650     return (var_Error);
2651 }
2652 
2653 /*-
2654  *-----------------------------------------------------------------------
2655  * Var_Subst  --
2656  *	Substitute for all variables in the given string in the given context
2657  *	If undefErr is TRUE, Parse_Error will be called when an undefined
2658  *	variable is encountered.
2659  *
2660  * Results:
2661  *	The resulting string.
2662  *
2663  * Side Effects:
2664  *	None. The old string must be freed by the caller
2665  *-----------------------------------------------------------------------
2666  */
2667 char *
2668 Var_Subst (var, str, ctxt, undefErr)
2669     char	  *var;		    /* Named variable || NULL for all */
2670     char 	  *str;	    	    /* the string in which to substitute */
2671     GNode         *ctxt;	    /* the context wherein to find variables */
2672     Boolean 	  undefErr; 	    /* TRUE if undefineds are an error */
2673 {
2674     Buffer  	  buf;	    	    /* Buffer for forming things */
2675     char    	  *val;		    /* Value to substitute for a variable */
2676     int	    	  length;   	    /* Length of the variable invocation */
2677     Boolean 	  doFree;   	    /* Set true if val should be freed */
2678     static Boolean errorReported;   /* Set true if an error has already
2679 				     * been reported to prevent a plethora
2680 				     * of messages when recursing */
2681 
2682     buf = Buf_Init (MAKE_BSIZE);
2683     errorReported = FALSE;
2684 
2685     while (*str) {
2686 	if (var == NULL && (*str == '$') && (str[1] == '$')) {
2687 	    /*
2688 	     * A dollar sign may be escaped either with another dollar sign.
2689 	     * In such a case, we skip over the escape character and store the
2690 	     * dollar sign into the buffer directly.
2691 	     */
2692 	    str++;
2693 	    Buf_AddByte(buf, (Byte)*str);
2694 	    str++;
2695 	} else if (*str != '$') {
2696 	    /*
2697 	     * Skip as many characters as possible -- either to the end of
2698 	     * the string or to the next dollar sign (variable invocation).
2699 	     */
2700 	    char  *cp;
2701 
2702 	    for (cp = str++; *str != '$' && *str != '\0'; str++)
2703 		continue;
2704 	    Buf_AddBytes(buf, str - cp, (Byte *)cp);
2705 	} else {
2706 	    if (var != NULL) {
2707 		int expand;
2708 		for (;;) {
2709 		    if (str[1] != '(' && str[1] != '{') {
2710 			if (str[1] != *var || strlen(var) > 1) {
2711 			    Buf_AddBytes(buf, 2, (Byte *) str);
2712 			    str += 2;
2713 			    expand = FALSE;
2714 			}
2715 			else
2716 			    expand = TRUE;
2717 			break;
2718 		    }
2719 		    else {
2720 			char *p;
2721 
2722 			/*
2723 			 * Scan up to the end of the variable name.
2724 			 */
2725 			for (p = &str[2]; *p &&
2726 			     *p != ':' && *p != ')' && *p != '}'; p++)
2727 			    if (*p == '$')
2728 				break;
2729 			/*
2730 			 * A variable inside the variable. We cannot expand
2731 			 * the external variable yet, so we try again with
2732 			 * the nested one
2733 			 */
2734 			if (*p == '$') {
2735 			    Buf_AddBytes(buf, p - str, (Byte *) str);
2736 			    str = p;
2737 			    continue;
2738 			}
2739 
2740 			if (strncmp(var, str + 2, p - str - 2) != 0 ||
2741 			    var[p - str - 2] != '\0') {
2742 			    /*
2743 			     * Not the variable we want to expand, scan
2744 			     * until the next variable
2745 			     */
2746 			    for (;*p != '$' && *p != '\0'; p++)
2747 				continue;
2748 			    Buf_AddBytes(buf, p - str, (Byte *) str);
2749 			    str = p;
2750 			    expand = FALSE;
2751 			}
2752 			else
2753 			    expand = TRUE;
2754 			break;
2755 		    }
2756 		}
2757 		if (!expand)
2758 		    continue;
2759 	    }
2760 
2761 	    val = Var_Parse (str, ctxt, undefErr, &length, &doFree);
2762 
2763 	    /*
2764 	     * When we come down here, val should either point to the
2765 	     * value of this variable, suitably modified, or be NULL.
2766 	     * Length should be the total length of the potential
2767 	     * variable invocation (from $ to end character...)
2768 	     */
2769 	    if (val == var_Error || val == varNoError) {
2770 		/*
2771 		 * If performing old-time variable substitution, skip over
2772 		 * the variable and continue with the substitution. Otherwise,
2773 		 * store the dollar sign and advance str so we continue with
2774 		 * the string...
2775 		 */
2776 		if (oldVars) {
2777 		    str += length;
2778 		} else if (undefErr) {
2779 		    /*
2780 		     * If variable is undefined, complain and skip the
2781 		     * variable. The complaint will stop us from doing anything
2782 		     * when the file is parsed.
2783 		     */
2784 		    if (!errorReported) {
2785 			Parse_Error (PARSE_FATAL,
2786 				     "Undefined variable \"%.*s\"",length,str);
2787 		    }
2788 		    str += length;
2789 		    errorReported = TRUE;
2790 		} else {
2791 		    Buf_AddByte (buf, (Byte)*str);
2792 		    str += 1;
2793 		}
2794 	    } else {
2795 		/*
2796 		 * We've now got a variable structure to store in. But first,
2797 		 * advance the string pointer.
2798 		 */
2799 		str += length;
2800 
2801 		/*
2802 		 * Copy all the characters from the variable value straight
2803 		 * into the new string.
2804 		 */
2805 		Buf_AddBytes (buf, strlen (val), (Byte *)val);
2806 		if (doFree) {
2807 		    free ((Address)val);
2808 		}
2809 	    }
2810 	}
2811     }
2812 
2813     Buf_AddByte (buf, '\0');
2814     str = (char *)Buf_GetAll (buf, (int *)NULL);
2815     Buf_Destroy (buf, FALSE);
2816     return (str);
2817 }
2818 
2819 /*-
2820  *-----------------------------------------------------------------------
2821  * Var_GetTail --
2822  *	Return the tail from each of a list of words. Used to set the
2823  *	System V local variables.
2824  *
2825  * Results:
2826  *	The resulting string.
2827  *
2828  * Side Effects:
2829  *	None.
2830  *
2831  *-----------------------------------------------------------------------
2832  */
2833 #if 0
2834 char *
2835 Var_GetTail(file)
2836     char    	*file;	    /* Filename to modify */
2837 {
2838     return(VarModify(file, VarTail, (ClientData)0));
2839 }
2840 
2841 /*-
2842  *-----------------------------------------------------------------------
2843  * Var_GetHead --
2844  *	Find the leading components of a (list of) filename(s).
2845  *	XXX: VarHead does not replace foo by ., as (sun) System V make
2846  *	does.
2847  *
2848  * Results:
2849  *	The leading components.
2850  *
2851  * Side Effects:
2852  *	None.
2853  *
2854  *-----------------------------------------------------------------------
2855  */
2856 char *
2857 Var_GetHead(file)
2858     char    	*file;	    /* Filename to manipulate */
2859 {
2860     return(VarModify(file, VarHead, (ClientData)0));
2861 }
2862 #endif
2863 
2864 /*-
2865  *-----------------------------------------------------------------------
2866  * Var_Init --
2867  *	Initialize the module
2868  *
2869  * Results:
2870  *	None
2871  *
2872  * Side Effects:
2873  *	The VAR_CMD and VAR_GLOBAL contexts are created
2874  *-----------------------------------------------------------------------
2875  */
2876 void
2877 Var_Init ()
2878 {
2879     VAR_GLOBAL = Targ_NewGN ("Global");
2880     VAR_CMD = Targ_NewGN ("Command");
2881 
2882 }
2883 
2884 
2885 void
2886 Var_End ()
2887 {
2888 }
2889 
2890 
2891 /****************** PRINT DEBUGGING INFO *****************/
2892 static void
2893 VarPrintVar (vp)
2894     ClientData vp;
2895 {
2896     Var    *v = (Var *) vp;
2897     printf ("%-16s = %s\n", v->name, (char *) Buf_GetAll(v->val, (int *)NULL));
2898 }
2899 
2900 /*-
2901  *-----------------------------------------------------------------------
2902  * Var_Dump --
2903  *	print all variables in a context
2904  *-----------------------------------------------------------------------
2905  */
2906 void
2907 Var_Dump (ctxt)
2908     GNode          *ctxt;
2909 {
2910     Hash_Search search;
2911     Hash_Entry *h;
2912 
2913     for (h = Hash_EnumFirst(&ctxt->context, &search);
2914 	 h != NULL;
2915 	 h = Hash_EnumNext(&search)) {
2916 	    VarPrintVar(Hash_GetValue(h));
2917     }
2918 }
2919