2be503c50379d9b75d585d70b57028fc8fcf628d
[dragonfly.git] / usr.bin / make / var.c
1 /*-
2  * Copyright (c) 1988, 1989, 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1989 by Berkeley Softworks
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Adam de Boor.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  * @(#)var.c    8.3 (Berkeley) 3/19/94
39  * $FreeBSD: src/usr.bin/make/var.c,v 1.83 2005/02/11 10:49:01 harti Exp $
40  * $DragonFly: src/usr.bin/make/var.c,v 1.184 2005/04/15 20:45:48 okumoto Exp $
41  */
42
43 /*-
44  * var.c --
45  *      Variable-handling functions
46  *
47  * Interface:
48  *      Var_Set         Set the value of a variable in the given
49  *                      context. The variable is created if it doesn't
50  *                      yet exist. The value and variable name need not
51  *                      be preserved.
52  *
53  *      Var_Append      Append more characters to an existing variable
54  *                      in the given context. The variable needn't
55  *                      exist already -- it will be created if it doesn't.
56  *                      A space is placed between the old value and the
57  *                      new one.
58  *
59  *      Var_Exists      See if a variable exists.
60  *
61  *      Var_Value       Return the value of a variable in a context or
62  *                      NULL if the variable is undefined.
63  *
64  *      Var_Subst       Substitute named variable, or all variables if
65  *                      NULL in a string using
66  *                      the given context as the top-most one. If the
67  *                      third argument is non-zero, Parse_Error is
68  *                      called if any variables are undefined.
69  *
70  *      Var_Parse       Parse a variable expansion from a string and
71  *                      return the result and the number of characters
72  *                      consumed.
73  *
74  *      Var_Delete      Delete a variable in a context.
75  *
76  *      Var_Init        Initialize this module.
77  *
78  * Debugging:
79  *      Var_Dump        Print out all variables defined in the given
80  *                      context.
81  *
82  * XXX: There's a lot of duplication in these functions.
83  */
84
85 #include <assert.h>
86 #include <ctype.h>
87 #include <stdlib.h>
88 #include <string.h>
89
90 #include "buf.h"
91 #include "config.h"
92 #include "globals.h"
93 #include "GNode.h"
94 #include "make.h"
95 #include "nonints.h"
96 #include "parse.h"
97 #include "str.h"
98 #include "targ.h"
99 #include "util.h"
100 #include "var.h"
101
102 /**
103  *
104  */
105 typedef struct VarParser {
106         const char      *const input;   /* pointer to input string */
107         const char      *ptr;           /* current parser pos in input str */
108         GNode           *ctxt;
109         Boolean         err;
110 } VarParser;
111 static char *VarParse(VarParser *, Boolean *);
112
113 /*
114  * This is a harmless return value for Var_Parse that can be used by Var_Subst
115  * to determine if there was an error in parsing -- easier than returning
116  * a flag, as things outside this module don't give a hoot.
117  */
118 char    var_Error[] = "";
119
120 /*
121  * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
122  * set false. Why not just use a constant? Well, gcc likes to condense
123  * identical string instances...
124  */
125 static char     varNoError[] = "";
126
127 /*
128  * Internally, variables are contained in four different contexts.
129  *      1) the environment. They may not be changed. If an environment
130  *         variable is appended-to, the result is placed in the global
131  *         context.
132  *      2) the global context. Variables set in the Makefile are located in
133  *         the global context. It is the penultimate context searched when
134  *         substituting.
135  *      3) the command-line context. All variables set on the command line
136  *         are placed in this context. They are UNALTERABLE once placed here.
137  *      4) the local context. Each target has associated with it a context
138  *         list. On this list are located the structures describing such
139  *         local variables as $(@) and $(*)
140  * The four contexts are searched in the reverse order from which they are
141  * listed.
142  */
143 GNode   *VAR_GLOBAL;    /* variables from the makefile */
144 GNode   *VAR_CMD;       /* variables defined on the command-line */
145
146 #define OPEN_PAREN              '('
147 #define CLOSE_PAREN             ')'
148 #define OPEN_BRACE              '{'
149 #define CLOSE_BRACE             '}'
150
151 /*
152  * Create a Var object.
153  *
154  * @param name          Name of variable.
155  * @param value         Value of variable.
156  * @param flags         Flags set on variable.
157  */
158 static Var *
159 VarCreate(const char name[], const char value[], int flags)
160 {
161         Var *v;
162
163         v = emalloc(sizeof(Var));
164         v->name = estrdup(name);
165         v->val  = Buf_Init(0);
166         v->flags        = flags;
167
168         if (value != NULL) {
169                 Buf_Append(v->val, value);
170         }
171         return (v);
172 }
173
174 /*
175  * Destroy a Var object.
176  *
177  * @param v     Object to destroy.
178  * @param f     true if internal buffer in Buffer object is to be
179  *              removed.
180  */
181 static void
182 VarDestroy(Var *v, Boolean f)
183 {
184
185         Buf_Destroy(v->val, f);
186         free(v->name);
187         free(v);
188 }
189
190 /*
191  * Find a variable in a variable list.
192  */
193 static Var *
194 VarLookup(Lst *vlist, const char *name)
195 {
196         LstNode *ln;
197
198         LST_FOREACH(ln, vlist)
199                 if (strcmp(((const Var *)Lst_Datum(ln))->name, name) == 0)
200                         return (Lst_Datum(ln));
201         return (NULL);
202 }
203
204 /*-
205  *-----------------------------------------------------------------------
206  * VarPossiblyExpand --
207  *      Expand a variable name's embedded variables in the given context.
208  *
209  * Results:
210  *      The contents of name, possibly expanded.
211  *-----------------------------------------------------------------------
212  */
213 static char *
214 VarPossiblyExpand(const char *name, GNode *ctxt)
215 {
216         Buffer  *buf;
217
218         if (strchr(name, '$') != NULL) {
219                 buf = Var_Subst(NULL, name, ctxt, 0);
220                 return (Buf_Peel(buf));
221         } else {
222                 return estrdup(name);
223         }
224 }
225
226 /**
227  * If the variable name begins with a '.', it could very well be
228  * one of the local ones.  We check the name against all the local
229  * variables and substitute the short version in for 'name' if it
230  * matches one of them.
231  */
232 static const char * 
233 VarLocal(const char name[])
234 {
235         if (name[0] == '.') {
236                 switch (name[1]) {
237                 case 'A':
238                         if (!strcmp(name, ".ALLSRC"))
239                                 return (ALLSRC);
240                         if (!strcmp(name, ".ARCHIVE"))
241                                 return (ARCHIVE);
242                         break;
243                 case 'I':
244                         if (!strcmp(name, ".IMPSRC"))
245                                 return (IMPSRC);
246                         break;
247                 case 'M':
248                         if (!strcmp(name, ".MEMBER"))
249                                 return (MEMBER);
250                         break;
251                 case 'O':
252                         if (!strcmp(name, ".OODATE"))
253                                 return (OODATE);
254                         break;
255                 case 'P':
256                         if (!strcmp(name, ".PREFIX"))
257                                 return (PREFIX);
258                         break;
259                 case 'T':
260                         if (!strcmp(name, ".TARGET"))
261                                 return (TARGET);
262                         break;
263                 default:
264                         break;
265                 }
266         }
267         return (name);
268 }
269
270 /**
271  * Find the given variable in the given context and the enviornment.
272  *
273  * Results:
274  *      A pointer to the structure describing the desired variable or
275  *      NULL if the variable does not exist.
276  */
277 static Var *
278 VarFindEnv(const char name[], GNode *ctxt)
279 {
280         Var     *var;
281         char    *env;
282
283         name = VarLocal(name);
284
285         /* First look for the variable in the given context. */
286         if ((var = VarLookup(&ctxt->context, name)) != NULL)
287                 return (var);
288
289         /* Look for the variable in the environment. */
290         if ((env = getenv(name)) != NULL) {
291                 /* craft this variable from the environment value */
292                 return (VarCreate(name, env, VAR_FROM_ENV));
293         }
294
295         return (NULL);
296 }
297
298 /**
299  * Look for the variable in the given context.
300  */
301 static Var *
302 VarFindOnly(const char name[], GNode *ctxt)
303 {
304
305         return VarLookup(&ctxt->context, VarLocal(name));
306 }
307
308 /**
309  * Look for the variable in all contexts.
310  */
311 static Var *
312 VarFindAny(const char name[], GNode *ctxt)
313 {
314         Boolean localCheckEnvFirst;
315         LstNode *ln;
316         Var     *var;
317         char    *env;
318
319         name = VarLocal(name);
320
321         /*
322          * Note whether this is one of the specific variables we were told
323          * through the -E flag to use environment-variable-override for.
324          */
325         localCheckEnvFirst = FALSE;
326         LST_FOREACH(ln, &envFirstVars) {
327                 if (strcmp(Lst_Datum(ln), name) == 0) {
328                         localCheckEnvFirst = TRUE;
329                         break;
330                 }
331         }
332
333         /*
334          * First look for the variable in the given context. If it's not there,
335          * look for it in VAR_CMD, VAR_GLOBAL and the environment,
336          * in that order, depending on the FIND_* flags in 'flags'
337          */
338         if ((var = VarLookup(&ctxt->context, name)) != NULL)
339                 return (var);
340
341         /* not there - try command line context */
342         if (ctxt != VAR_CMD) {
343                 if ((var = VarLookup(&VAR_CMD->context, name)) != NULL)
344                         return (var);
345         }
346
347         /* not there - try global context, but only if not -e/-E */
348         if (ctxt != VAR_GLOBAL && (!checkEnvFirst && !localCheckEnvFirst)) {
349                 if ((var = VarLookup(&VAR_GLOBAL->context, name)) != NULL)
350                         return (var);
351         }
352
353         /* look in the environment */
354         if ((env = getenv(name)) != NULL) {
355                 /* craft this variable from the environment value */
356                 return (VarCreate(name, env, VAR_FROM_ENV));
357         }
358
359         /* deferred check for the environment (in case of -e/-E) */
360         if ((ctxt != VAR_GLOBAL) && (checkEnvFirst || localCheckEnvFirst)) {
361                 if ((var = VarLookup(&VAR_GLOBAL->context, name)) != NULL)
362                         return (var);
363         }
364
365         return (NULL);
366 }
367
368 /*-
369  *-----------------------------------------------------------------------
370  * VarAdd  --
371  *      Add a new variable of name name and value val to the given context.
372  *
373  * Results:
374  *      None
375  *
376  * Side Effects:
377  *      The new variable is placed at the front of the given context
378  *      The name and val arguments are duplicated so they may
379  *      safely be freed.
380  *-----------------------------------------------------------------------
381  */
382 static void
383 VarAdd(const char *name, const char *val, GNode *ctxt)
384 {
385
386         Lst_AtFront(&ctxt->context, VarCreate(name, val, 0));
387         DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
388 }
389
390 /*-
391  *-----------------------------------------------------------------------
392  * Var_Delete --
393  *      Remove a variable from a context.
394  *
395  * Results:
396  *      None.
397  *
398  * Side Effects:
399  *      The Var structure is removed and freed.
400  *
401  *-----------------------------------------------------------------------
402  */
403 void
404 Var_Delete(const char *name, GNode *ctxt)
405 {
406         LstNode *ln;
407
408         DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
409         LST_FOREACH(ln, &ctxt->context) {
410                 if (strcmp(((const Var *)Lst_Datum(ln))->name, name) == 0) {
411                         VarDestroy(Lst_Datum(ln), TRUE);
412                         Lst_Remove(&ctxt->context, ln);
413                         break;
414                 }
415         }
416 }
417
418 /*-
419  *-----------------------------------------------------------------------
420  * Var_Set --
421  *      Set the variable name to the value val in the given context.
422  *
423  * Results:
424  *      None.
425  *
426  * Side Effects:
427  *      If the variable doesn't yet exist, a new record is created for it.
428  *      Else the old value is freed and the new one stuck in its place
429  *
430  * Notes:
431  *      The variable is searched for only in its context before being
432  *      created in that context. I.e. if the context is VAR_GLOBAL,
433  *      only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
434  *      VAR_CMD->context is searched. This is done to avoid the literally
435  *      thousands of unnecessary strcmp's that used to be done to
436  *      set, say, $(@) or $(<).
437  *-----------------------------------------------------------------------
438  */
439 void
440 Var_Set(const char *name, const char *val, GNode *ctxt)
441 {
442         Var    *v;
443         char   *n;
444
445         /*
446          * We only look for a variable in the given context since anything
447          * set here will override anything in a lower context, so there's not
448          * much point in searching them all just to save a bit of memory...
449          */
450         n = VarPossiblyExpand(name, ctxt);
451         v = VarFindOnly(n, ctxt);
452         if (v == NULL) {
453                 VarAdd(n, val, ctxt);
454         } else {
455                 Buf_Clear(v->val);
456                 Buf_Append(v->val, val);
457
458                 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, val));
459         }
460         /*
461          * Any variables given on the command line are automatically exported
462          * to the environment (as per POSIX standard)
463          */
464         if (ctxt == VAR_CMD || (v != NULL && (v->flags & VAR_TO_ENV))) {
465                 setenv(n, val, 1);
466         }
467         free(n);
468 }
469
470 /*
471  * Var_SetEnv --
472  *      Set the VAR_TO_ENV flag on a variable
473  */
474 void
475 Var_SetEnv(const char *name, GNode *ctxt)
476 {
477         Var    *v;
478
479         v = VarFindAny(name, ctxt);
480         if (v == NULL) {
481                 Error("Cannot set environment flag on non-existant variable %s", name);
482         } else {
483                 if ((v->flags & VAR_TO_ENV) == 0) {
484                         v->flags |= VAR_TO_ENV;
485                         setenv(v->name, Buf_Data(v->val), 1);
486                 }
487         }
488 }
489
490 /*-
491  *-----------------------------------------------------------------------
492  * Var_Append --
493  *      The variable of the given name has the given value appended to it in
494  *      the given context.
495  *
496  * Results:
497  *      None
498  *
499  * Side Effects:
500  *      If the variable doesn't exist, it is created. Else the strings
501  *      are concatenated (with a space in between).
502  *
503  * Notes:
504  *      Only if the variable is being sought in the global context is the
505  *      environment searched.
506  *      XXX: Knows its calling circumstances in that if called with ctxt
507  *      an actual target, it will only search that context since only
508  *      a local variable could be being appended to. This is actually
509  *      a big win and must be tolerated.
510  *-----------------------------------------------------------------------
511  */
512 void
513 Var_Append(const char *name, const char *val, GNode *ctxt)
514 {
515         Var     *v;
516         char    *n;
517
518         n = VarPossiblyExpand(name, ctxt);
519         if (ctxt == VAR_GLOBAL) {
520                 v = VarFindEnv(n, ctxt);
521         } else {
522                 v = VarFindOnly(n, ctxt);
523         }
524         if (v == NULL) {
525                 VarAdd(n, val, ctxt);
526
527         } else if (v->flags & VAR_FROM_ENV) {
528                 Buf_AddByte(v->val, (Byte)' ');
529                 Buf_Append(v->val, val);
530                 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, Buf_Data(v->val)));
531                 /*
532                  * If the original variable came from the
533                  * environment, we have to install it in the global
534                  * context (we could place it in the environment, but
535                  * then we should provide a way to export other
536                  * variables...)
537                  */
538                 v->flags &= ~VAR_FROM_ENV;
539                 Lst_AtFront(&ctxt->context, v);
540
541         } else {
542                 Buf_AddByte(v->val, (Byte)' ');
543                 Buf_Append(v->val, val);
544                 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, Buf_Data(v->val)));
545         }
546         free(n);
547 }
548
549 /*-
550  *-----------------------------------------------------------------------
551  * Var_Exists --
552  *      See if the given variable exists.
553  *
554  * Results:
555  *      TRUE if it does, FALSE if it doesn't
556  *
557  * Side Effects:
558  *      None.
559  *
560  *-----------------------------------------------------------------------
561  */
562 Boolean
563 Var_Exists(const char *name, GNode *ctxt)
564 {
565         Var     *v;
566         char    *n;
567
568         n = VarPossiblyExpand(name, ctxt);
569         v = VarFindAny(n, ctxt);
570         if (v == NULL) {
571                 free(n);
572                 return (FALSE);
573         } else if (v->flags & VAR_FROM_ENV) {
574                 VarDestroy(v, TRUE);
575                 free(n);
576                 return (TRUE);
577         } else {
578                 free(n);
579                 return (TRUE);
580         }
581 }
582
583 /*-
584  *-----------------------------------------------------------------------
585  * Var_Value --
586  *      Return the value of the named variable in the given context
587  *
588  * Results:
589  *      The value if the variable exists, NULL if it doesn't
590  *
591  * Side Effects:
592  *      None
593  *-----------------------------------------------------------------------
594  */
595 char *
596 Var_Value(const char *name, GNode *ctxt, char **frp)
597 {
598         Var     *v;
599         char    *n;
600         char    *p;
601
602         n = VarPossiblyExpand(name, ctxt);
603         v = VarFindAny(n, ctxt);
604         if (v == NULL) {
605                 p = NULL;
606                 *frp = NULL;
607         } else if (v->flags & VAR_FROM_ENV) {
608                 p = Buf_Data(v->val);
609                 *frp = p;
610                 VarDestroy(v, FALSE);
611         } else {
612                 p = Buf_Data(v->val);
613                 *frp = NULL;
614         }
615         free(n);
616         return (p);
617 }
618
619 /*-
620  *-----------------------------------------------------------------------
621  * VarModify --
622  *      Modify each of the words of the passed string using the given
623  *      function. Used to implement all modifiers.
624  *
625  * Results:
626  *      A string of all the words modified appropriately.
627  *
628  * Side Effects:
629  *      Uses brk_string() so it invalidates any previous call to
630  *      brk_string().
631  *
632  *-----------------------------------------------------------------------
633  */
634 static char *
635 VarModify(const char *str, VarModifyProc *modProc, void *datum)
636 {
637         char    **av;           /* word list [first word does not count] */
638         int     ac;
639         Buffer  *buf;           /* Buffer for the new string */
640         Boolean addSpace;       /* TRUE if need to add a space to the buffer
641                                  * before adding the trimmed word */
642         int     i;
643
644         av = brk_string(str, &ac, FALSE);
645
646         buf = Buf_Init(0);
647
648         addSpace = FALSE;
649         for (i = 1; i < ac; i++)
650                 addSpace = (*modProc)(av[i], addSpace, buf, datum);
651
652         return (Buf_Peel(buf));
653 }
654
655 /*-
656  *-----------------------------------------------------------------------
657  * VarSortWords --
658  *      Sort the words in the string.
659  *
660  * Input:
661  *      str             String whose words should be sorted
662  *      cmp             A comparison function to control the ordering
663  *
664  * Results:
665  *      A string containing the words sorted
666  *
667  * Side Effects:
668  *      Uses brk_string() so it invalidates any previous call to
669  *      brk_string().
670  *
671  *-----------------------------------------------------------------------
672  */
673 static char *
674 VarSortWords(const char *str, int (*cmp)(const void *, const void *))
675 {
676         char    **av;
677         int     ac;
678         Buffer  *buf;
679         int     i;
680
681         av = brk_string(str, &ac, FALSE);
682         qsort(av + 1, ac - 1, sizeof(char *), cmp);
683
684         buf = Buf_Init(0);
685         for (i = 1; i < ac; i++) {
686                 Buf_Append(buf, av[i]);
687                 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
688         }
689
690         return (Buf_Peel(buf));
691 }
692
693 static int
694 SortIncreasing(const void *l, const void *r)
695 {
696
697         return (strcmp(*(const char* const*)l, *(const char* const*)r));
698 }
699
700 /*-
701  *-----------------------------------------------------------------------
702  * VarGetPattern --
703  *      Pass through the tstr looking for 1) escaped delimiters,
704  *      '$'s and backslashes (place the escaped character in
705  *      uninterpreted) and 2) unescaped $'s that aren't before
706  *      the delimiter (expand the variable substitution).
707  *      Return the expanded string or NULL if the delimiter was missing
708  *      If pattern is specified, handle escaped ampersands, and replace
709  *      unescaped ampersands with the lhs of the pattern.
710  *
711  * Results:
712  *      A string of all the words modified appropriately.
713  *      If length is specified, return the string length of the buffer
714  *      If flags is specified and the last character of the pattern is a
715  *      $ set the VAR_MATCH_END bit of flags.
716  *
717  * Side Effects:
718  *      None.
719  *-----------------------------------------------------------------------
720  */
721 static Buffer *
722 VarGetPattern(VarParser *vp, int delim, int *flags, VarPattern *patt)
723 {
724         Buffer          *buf;
725
726         buf = Buf_Init(0);
727
728         /*
729          * Skim through until the matching delimiter is found; pick up
730          * variable substitutions on the way. Also allow backslashes to quote
731          * the delimiter, $, and \, but don't touch other backslashes.
732          */
733         while (*vp->ptr != '\0') {
734                 if (*vp->ptr == delim) {
735                         return (buf);
736
737                 } else if ((vp->ptr[0] == '\\') &&
738                     ((vp->ptr[1] == delim) ||
739                      (vp->ptr[1] == '\\') ||
740                      (vp->ptr[1] == '$') ||
741                      (vp->ptr[1] == '&' && patt != NULL))) {
742                         vp->ptr++;              /* consume backslash */
743                         Buf_AddByte(buf, (Byte)vp->ptr[0]);
744                         vp->ptr++;
745
746                 } else if (vp->ptr[0] == '$') {
747                         if (vp->ptr[1] == delim) {
748                                 if (flags == NULL) {
749                                         Buf_AddByte(buf, (Byte)vp->ptr[0]);
750                                         vp->ptr++;
751                                 } else {
752                                         /*
753                                          * Unescaped $ at end of patt =>
754                                          * anchor patt at end.
755                                          */
756                                         *flags |= VAR_MATCH_END;
757                                         vp->ptr++;
758                                 }
759                         } else {
760                                 VarParser       subvp = {
761                                         vp->ptr,
762                                         vp->ptr,
763                                         vp->ctxt,
764                                         vp->err
765                                 };
766                                 char   *rval;
767                                 Boolean rfree;
768
769                                 /*
770                                  * If unescaped dollar sign not
771                                  * before the delimiter, assume it's
772                                  * a variable substitution and
773                                  * recurse.
774                                  */
775                                 rval = VarParse(&subvp, &rfree);
776                                 Buf_Append(buf, rval);
777                                 if (rfree)
778                                         free(rval);
779                                 vp->ptr = subvp.ptr;
780                         }
781                 } else if (vp->ptr[0] == '&' && patt != NULL) {
782                         Buf_AppendBuf(buf, patt->lhs);
783                         vp->ptr++;
784                 } else {
785                         Buf_AddByte(buf, (Byte)vp->ptr[0]);
786                         vp->ptr++;
787                 }
788         }
789
790         Buf_Destroy(buf, TRUE);
791         return (NULL);
792 }
793
794 /*-
795  *-----------------------------------------------------------------------
796  * Var_Quote --
797  *      Quote shell meta-characters in the string
798  *
799  * Results:
800  *      The quoted string
801  *
802  * Side Effects:
803  *      None.
804  *
805  *-----------------------------------------------------------------------
806  */
807 char *
808 Var_Quote(const char *str)
809 {
810         Buffer *buf;
811         /* This should cover most shells :-( */
812         static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
813
814         buf = Buf_Init(MAKE_BSIZE);
815         for (; *str; str++) {
816                 if (strchr(meta, *str) != NULL)
817                         Buf_AddByte(buf, (Byte)'\\');
818                 Buf_AddByte(buf, (Byte)*str);
819         }
820
821         return (Buf_Peel(buf));
822 }
823
824 /*-
825  *-----------------------------------------------------------------------
826  * VarREError --
827  *      Print the error caused by a regcomp or regexec call.
828  *
829  * Results:
830  *      None.
831  *
832  * Side Effects:
833  *      An error gets printed.
834  *
835  *-----------------------------------------------------------------------
836  */
837 void
838 VarREError(int err, regex_t *pat, const char *str)
839 {
840         char   *errbuf;
841         int     errlen;
842
843         errlen = regerror(err, pat, 0, 0);
844         errbuf = emalloc(errlen);
845         regerror(err, pat, errbuf, errlen);
846         Error("%s: %s", str, errbuf);
847         free(errbuf);
848 }
849
850 /**
851  * Make sure this variable is fully expanded.
852  */
853 static char *
854 VarExpand(Var *v, VarParser *vp)
855 {
856         char    *value;
857         char    *result;
858
859         if (v->flags & VAR_IN_USE) {
860                 Fatal("Variable %s is recursive.", v->name);
861                 /* NOTREACHED */
862         }
863
864         v->flags |= VAR_IN_USE;
865
866         /*
867          * Before doing any modification, we have to make sure the
868          * value has been fully expanded. If it looks like recursion
869          * might be necessary (there's a dollar sign somewhere in the
870          * variable's value) we just call Var_Subst to do any other
871          * substitutions that are necessary. Note that the value
872          * returned by Var_Subst will have been
873          * dynamically-allocated, so it will need freeing when we
874          * return.
875          */
876         value = Buf_Data(v->val);
877         if (strchr(value, '$') == NULL) {
878                 result = strdup(value);
879         } else {
880                 Buffer  *buf;
881
882                 buf = Var_Subst(NULL, value, vp->ctxt, vp->err);
883                 result = Buf_Peel(buf);
884         }
885
886         v->flags &= ~VAR_IN_USE;
887
888         return (result);
889 }
890
891 /**
892  * Select only those words in value that match the modifier.
893  */
894 static char *
895 modifier_M(VarParser *vp, const char value[], char endc)
896 {
897         char    *patt;
898         char    *ptr;
899         char    *newValue;
900         char    modifier;
901
902         modifier = vp->ptr[0];
903         vp->ptr++;      /* consume 'M' or 'N' */
904
905         /*
906          * Compress the \:'s out of the pattern, so allocate enough
907          * room to hold the uncompressed pattern and compress the
908          * pattern into that space.
909          */
910         patt = estrdup(vp->ptr);
911         ptr = patt;
912         while (vp->ptr[0] != '\0') {
913                 if (vp->ptr[0] == endc || vp->ptr[0] == ':') {
914                         break;
915                 }
916                 if (vp->ptr[0] == '\\' &&
917                     (vp->ptr[1] == endc || vp->ptr[1] == ':')) {
918                         vp->ptr++;      /* consume backslash */
919                 }
920                 *ptr = vp->ptr[0];
921                 ptr++;
922                 vp->ptr++;
923         }
924         *ptr = '\0';
925
926         if (modifier == 'M') {
927                 newValue = VarModify(value, VarMatch, patt);
928         } else {
929                 newValue = VarModify(value, VarNoMatch, patt);
930         }
931         free(patt);
932
933         return (newValue);
934 }
935
936 /**
937  * Substitute the replacement string for the pattern.  The substitution
938  * is applied to each word in value.
939  */
940 static char *
941 modifier_S(VarParser *vp, const char value[], Var *v)
942 {
943         VarPattern      patt;
944         char            delim;
945         char            *newValue;
946
947         patt.flags = 0;
948
949         vp->ptr++;              /* consume 'S' */
950
951         delim = *vp->ptr;       /* used to find end of pattern */
952         vp->ptr++;              /* consume 1st delim */
953
954         /*
955          * If pattern begins with '^', it is anchored to the start of the
956          * word -- skip over it and flag pattern.
957          */
958         if (*vp->ptr == '^') {
959                 patt.flags |= VAR_MATCH_START;
960                 vp->ptr++;
961         }
962
963         patt.lhs = VarGetPattern(vp, delim, &patt.flags, NULL);
964         if (patt.lhs == NULL) {
965                 /*
966                  * LHS didn't end with the delim, complain and exit.
967                  */
968                 Fatal("Unclosed substitution for %s (%c missing)",
969                     v->name, delim);
970         }
971
972         vp->ptr++;      /* consume 2nd delim */
973
974         patt.rhs = VarGetPattern(vp, delim, NULL, &patt);
975         if (patt.rhs == NULL) {
976                 /*
977                  * RHS didn't end with the delim, complain and exit.
978                  */
979                 Fatal("Unclosed substitution for %s (%c missing)",
980                     v->name, delim);
981         }
982
983         vp->ptr++;      /* consume last delim */
984
985         /*
986          * Check for global substitution. If 'g' after the final delimiter,
987          * substitution is global and is marked that way.
988          */
989         if (vp->ptr[0] == 'g') {
990                 patt.flags |= VAR_SUB_GLOBAL;
991                 vp->ptr++;
992         }
993
994         /*
995          * Global substitution of the empty string causes an infinite number
996          * of matches, unless anchored by '^' (start of string) or '$' (end
997          * of string). Catch the infinite substitution here. Note that flags
998          * can only contain the 3 bits we're interested in so we don't have
999          * to mask unrelated bits. We can test for equality.
1000          */
1001         if (Buf_Size(patt.lhs) == 0 && patt.flags == VAR_SUB_GLOBAL)
1002                 Fatal("Global substitution of the empty string");
1003
1004         newValue = VarModify(value, VarSubstitute, &patt);
1005
1006         /*
1007          * Free the two strings.
1008          */
1009         free(patt.lhs);
1010         free(patt.rhs);
1011
1012         return (newValue);
1013 }
1014
1015 static char *
1016 modifier_C(VarParser *vp, char value[], Var *v)
1017 {
1018         VarPattern      patt;
1019         char            delim;
1020         int             error;
1021         char            *newValue;
1022
1023         patt.flags = 0;
1024
1025         vp->ptr++;              /* consume 'C' */
1026
1027         delim = *vp->ptr;       /* delimiter between sections */
1028
1029         vp->ptr++;              /* consume 1st delim */
1030
1031         patt.lhs = VarGetPattern(vp, delim, NULL, NULL);
1032         if (patt.lhs == NULL) {
1033                 Fatal("Unclosed substitution for %s (%c missing)",
1034                      v->name, delim);
1035         }
1036
1037         vp->ptr++;              /* consume 2st delim */
1038
1039         patt.rhs = VarGetPattern(vp, delim, NULL, NULL);
1040         if (patt.rhs == NULL) {
1041                 Fatal("Unclosed substitution for %s (%c missing)",
1042                      v->name, delim);
1043         }
1044
1045         vp->ptr++;              /* consume last delim */
1046
1047         switch (*vp->ptr) {
1048         case 'g':
1049                 patt.flags |= VAR_SUB_GLOBAL;
1050                 vp->ptr++;              /* consume 'g' */
1051                 break;
1052         case '1':
1053                 patt.flags |= VAR_SUB_ONE;
1054                 vp->ptr++;              /* consume '1' */
1055                 break;
1056         default:
1057                 break;
1058         }
1059
1060         error = regcomp(&patt.re, Buf_Data(patt.lhs), REG_EXTENDED);
1061         if (error) {
1062                 VarREError(error, &patt.re, "RE substitution error");
1063                 free(patt.rhs);
1064                 free(patt.lhs);
1065                 return (var_Error);
1066         }
1067
1068         patt.nsub = patt.re.re_nsub + 1;
1069         if (patt.nsub < 1)
1070                 patt.nsub = 1;
1071         if (patt.nsub > 10)
1072                 patt.nsub = 10;
1073         patt.matches = emalloc(patt.nsub * sizeof(regmatch_t));
1074
1075         newValue = VarModify(value, VarRESubstitute, &patt);
1076
1077         regfree(&patt.re);
1078         free(patt.matches);
1079         free(patt.rhs);
1080         free(patt.lhs);
1081
1082         return (newValue);
1083 }
1084
1085 static char *
1086 sysVvarsub(VarParser *vp, char startc, Var *v, const char value[])
1087 {
1088 #ifdef SYSVVARSUB
1089         /*
1090          * This can either be a bogus modifier or a System-V substitution
1091          * command.
1092          */
1093         char            endc;
1094         VarPattern      patt;
1095         Boolean         eqFound;
1096         int             cnt;
1097         char            *newStr;
1098         const char      *cp;
1099
1100         endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1101
1102         patt.flags = 0;
1103
1104         /*
1105          * First we make a pass through the string trying to verify it is a
1106          * SYSV-make-style translation: it must be: <string1>=<string2>)
1107          */
1108         eqFound = FALSE;
1109         cp = vp->ptr;
1110         cnt = 1;
1111         while (*cp != '\0' && cnt) {
1112                 if (*cp == '=') {
1113                         eqFound = TRUE;
1114                         /* continue looking for endc */
1115                 } else if (*cp == endc)
1116                         cnt--;
1117                 else if (*cp == startc)
1118                         cnt++;
1119                 if (cnt)
1120                         cp++;
1121         }
1122
1123         if (*cp == endc && eqFound) {
1124                 /*
1125                  * Now we break this sucker into the lhs and rhs.
1126                  */
1127                 patt.lhs = VarGetPattern(vp, '=', &patt.flags, NULL);
1128                 if (patt.lhs == NULL) {
1129                         Fatal("Unclosed substitution for %s (%c missing)",
1130                               v->name, '=');
1131                 }
1132                 vp->ptr++;      /* consume '=' */
1133
1134                 patt.rhs = VarGetPattern(vp, endc, NULL, &patt);
1135                 if (patt.rhs == NULL) {
1136                         Fatal("Unclosed substitution for %s (%c missing)",
1137                               v->name, endc);
1138                 }
1139
1140                 /*
1141                  * SYSV modifications happen through the whole string. Note
1142                  * the pattern is anchored at the end.
1143                  */
1144                 newStr = VarModify(value, VarSYSVMatch, &patt);
1145
1146                 free(patt.lhs);
1147                 free(patt.rhs);
1148         } else
1149 #endif
1150         {
1151                 Error("Unknown modifier '%c'\n", *vp->ptr);
1152                 vp->ptr++;
1153                 while (*vp->ptr != '\0') {
1154                         if (*vp->ptr == endc && *vp->ptr == ':') {
1155                                 break;
1156                         }
1157                         vp->ptr++;
1158                 }
1159                 newStr = var_Error;
1160         }
1161
1162         return (newStr);
1163 }
1164
1165 /*
1166  * Now we need to apply any modifiers the user wants applied.
1167  * These are:
1168  *      :M<pattern>
1169  *              words which match the given <pattern>.
1170  *              <pattern> is of the standard file
1171  *              wildcarding form.
1172  *      :S<d><pat1><d><pat2><d>[g]
1173  *              Substitute <pat2> for <pat1> in the value
1174  *      :C<d><pat1><d><pat2><d>[g]
1175  *              Substitute <pat2> for regex <pat1> in the value
1176  *      :H      Substitute the head of each word
1177  *      :T      Substitute the tail of each word
1178  *      :E      Substitute the extension (minus '.') of
1179  *              each word
1180  *      :R      Substitute the root of each word
1181  *              (pathname minus the suffix).
1182  *      :lhs=rhs
1183  *              Like :S, but the rhs goes to the end of
1184  *              the invocation.
1185  *      :U      Converts variable to upper-case.
1186  *      :L      Converts variable to lower-case.
1187  *
1188  * XXXHB update this comment or remove it and point to the man page.
1189  */
1190 static char *
1191 ParseModifier(VarParser *vp, char startc, Var *v, Boolean *freeResult)
1192 {
1193         char    *value;
1194         char    endc;
1195
1196         value = VarExpand(v, vp);
1197         *freeResult = TRUE;
1198
1199         endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1200
1201         vp->ptr++;      /* consume first colon */
1202
1203         while (*vp->ptr != '\0') {
1204                 char    *newStr;        /* New value to return */
1205
1206                 if (*vp->ptr == endc) {
1207                         return (value);
1208                 }
1209
1210                 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *vp->ptr, value));
1211                 switch (*vp->ptr) {
1212                 case 'N':
1213                 case 'M':
1214                         newStr = modifier_M(vp, value, endc);
1215                         break;
1216                 case 'S':
1217                         newStr = modifier_S(vp, value, v);
1218                         break;
1219                 case 'C':
1220                         newStr = modifier_C(vp, value, v);
1221                         break;
1222                 default:
1223                         if (vp->ptr[1] != endc && vp->ptr[1] != ':') {
1224 #ifdef SUNSHCMD
1225                                 if ((vp->ptr[0] == 's') &&
1226                                     (vp->ptr[1] == 'h') &&
1227                                     (vp->ptr[2] == endc || vp->ptr[2] == ':')) {
1228                                         const char      *error;
1229                                         Buffer          *buf;
1230
1231                                         buf = Cmd_Exec(value, &error);
1232                                         newStr = Buf_Peel(buf);
1233
1234                                         if (error)
1235                                                 Error(error, value);
1236                                         vp->ptr += 2;
1237                                 } else
1238 #endif
1239                                 {
1240                                         newStr = sysVvarsub(vp, startc, v, value);
1241                                 }
1242                                 break;
1243                         }
1244
1245                         switch (vp->ptr[0]) {
1246                         case 'L':
1247                                 {
1248                                 const char      *cp;
1249                                 Buffer          *buf;
1250                                 buf = Buf_Init(MAKE_BSIZE);
1251                                 for (cp = value; *cp; cp++)
1252                                         Buf_AddByte(buf, (Byte)tolower(*cp));
1253
1254                                 newStr = Buf_Peel(buf);
1255
1256                                 vp->ptr++;
1257                                 break;
1258                                 }
1259                         case 'O':
1260                                 newStr = VarSortWords(value, SortIncreasing);
1261                                 vp->ptr++;
1262                                 break;
1263                         case 'Q':
1264                                 newStr = Var_Quote(value);
1265                                 vp->ptr++;
1266                                 break;
1267                         case 'T':
1268                                 newStr = VarModify(value, VarTail, NULL);
1269                                 vp->ptr++;
1270                                 break;
1271                         case 'U':
1272                                 {
1273                                 const char      *cp;
1274                                 Buffer          *buf;
1275                                 buf = Buf_Init(MAKE_BSIZE);
1276                                 for (cp = value; *cp; cp++)
1277                                         Buf_AddByte(buf, (Byte)toupper(*cp));
1278
1279                                 newStr = Buf_Peel(buf);
1280
1281                                 vp->ptr++;
1282                                 break;
1283                                 }
1284                         case 'H':
1285                                 newStr = VarModify(value, VarHead, NULL);
1286                                 vp->ptr++;
1287                                 break;
1288                         case 'E':
1289                                 newStr = VarModify(value, VarSuffix, NULL);
1290                                 vp->ptr++;
1291                                 break;
1292                         case 'R':
1293                                 newStr = VarModify(value, VarRoot, NULL);
1294                                 vp->ptr++;
1295                                 break;
1296                         default:
1297                                 newStr = sysVvarsub(vp, startc, v, value);
1298                                 break;
1299                         }
1300                         break;
1301                 }
1302
1303                 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1304                 if (*freeResult) {
1305                         free(value);
1306                 }
1307
1308                 value = newStr;
1309                 *freeResult = (value == var_Error) ? FALSE : TRUE;
1310
1311                 if (vp->ptr[0] == ':') {
1312                         vp->ptr++;      /* consume colon */
1313                 }
1314         }
1315
1316         return (value);
1317 }
1318
1319 static char *
1320 ParseRestModifier(VarParser *vp, char startc, Buffer *buf, Boolean *freeResult)
1321 {
1322         const char      *vname;
1323         size_t          vlen;
1324         Var             *v;
1325         char            *value;
1326
1327         vname = Buf_GetAll(buf, &vlen);
1328
1329         v = VarFindAny(vname, vp->ctxt);
1330         if (v != NULL) {
1331                 value = ParseModifier(vp, startc, v, freeResult);
1332
1333                 if (v->flags & VAR_FROM_ENV) {
1334                         VarDestroy(v, TRUE);
1335                 }
1336                 return (value);
1337         }
1338
1339         if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1340                 size_t  consumed;
1341                 /*
1342                  * Still need to get to the end of the variable
1343                  * specification, so kludge up a Var structure for the
1344                  * modifications
1345                  */
1346                 v = VarCreate(vname, NULL, VAR_JUNK);
1347                 value = ParseModifier(vp, startc, v, freeResult);
1348                 if (*freeResult) {
1349                         free(value);
1350                 }
1351                 VarDestroy(v, TRUE);
1352
1353                 consumed = vp->ptr - vp->input + 1;
1354                 /*
1355                  * If substituting a local variable in a non-local context,
1356                  * assume it's for dynamic source stuff. We have to handle
1357                  * this specially and return the longhand for the variable
1358                  * with the dollar sign escaped so it makes it back to the
1359                  * caller. Only four of the local variables are treated
1360                  * specially as they are the only four that will be set when
1361                  * dynamic sources are expanded.
1362                  */
1363                 if (vlen == 1 ||
1364                     (vlen == 2 && (vname[1] == 'F' || vname[1] == 'D'))) {
1365                         if (strchr("!%*@", vname[0]) != NULL) {
1366                                 value = emalloc(consumed + 1);
1367                                 strncpy(value, vp->input, consumed);
1368                                 value[consumed] = '\0';
1369
1370                                 *freeResult = TRUE;
1371                                 return (value);
1372                         }
1373                 }
1374                 if (vlen > 2 &&
1375                     vname[0] == '.' &&
1376                     isupper((unsigned char)vname[1])) {
1377                         if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1378                             (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1379                             (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1380                             (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1381                                 value = emalloc(consumed + 1);
1382                                 strncpy(value, vp->input, consumed);
1383                                 value[consumed] = '\0';
1384
1385                                 *freeResult = TRUE;
1386                                 return (value);
1387                         }
1388                 }
1389
1390                 *freeResult = FALSE;
1391                 return (vp->err ? var_Error : varNoError);
1392         } else {
1393                 /*
1394                  * Check for D and F forms of local variables since we're in
1395                  * a local context and the name is the right length.
1396                  */
1397                 if (vlen == 2 &&
1398                     (vname[1] == 'F' || vname[1] == 'D') &&
1399                     (strchr("!%*<>@", vname[0]) != NULL)) {
1400                         char    name[2];
1401
1402                         name[0] = vname[0];
1403                         name[1] = '\0';
1404
1405                         v = VarFindOnly(name, vp->ctxt);
1406                         if (v != NULL) {
1407                                 value = ParseModifier(vp, startc, v, freeResult);
1408                                 return (value);
1409                         }
1410                 }
1411
1412                 /*
1413                  * Still need to get to the end of the variable
1414                  * specification, so kludge up a Var structure for the
1415                  * modifications
1416                  */
1417                 v = VarCreate(vname, NULL, VAR_JUNK);
1418                 value = ParseModifier(vp, startc, v, freeResult);
1419                 if (*freeResult) {
1420                         free(value);
1421                 }
1422                 VarDestroy(v, TRUE);
1423
1424                 *freeResult = FALSE;
1425                 return (vp->err ? var_Error : varNoError);
1426         }
1427 }
1428
1429 static char *
1430 ParseRestEnd(VarParser *vp, Buffer *buf, Boolean *freeResult)
1431 {
1432         const char      *vname;
1433         size_t          vlen;
1434         Var             *v;
1435         char            *value;
1436
1437         vname = Buf_GetAll(buf, &vlen);
1438
1439         v = VarFindAny(vname, vp->ctxt);
1440         if (v != NULL) {
1441                 value = VarExpand(v, vp);
1442
1443                 if (v->flags & VAR_FROM_ENV) {
1444                         VarDestroy(v, TRUE);
1445                 }
1446
1447                 *freeResult = TRUE;
1448                 return (value);
1449         }
1450
1451         if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1452                 size_t  consumed = vp->ptr - vp->input + 1;
1453
1454                 /*
1455                  * If substituting a local variable in a non-local context,
1456                  * assume it's for dynamic source stuff. We have to handle
1457                  * this specially and return the longhand for the variable
1458                  * with the dollar sign escaped so it makes it back to the
1459                  * caller. Only four of the local variables are treated
1460                  * specially as they are the only four that will be set when
1461                  * dynamic sources are expanded.
1462                  */
1463                 if (vlen == 1 ||
1464                     (vlen == 2 && (vname[1] == 'F' || vname[1] == 'D'))) {
1465                         if (strchr("!%*@", vname[0]) != NULL) {
1466                                 value = emalloc(consumed + 1);
1467                                 strncpy(value, vp->input, consumed);
1468                                 value[consumed] = '\0';
1469
1470                                 *freeResult = TRUE;
1471                                 return (value);
1472                         }
1473                 }
1474                 if (vlen > 2 &&
1475                     vname[0] == '.' &&
1476                     isupper((unsigned char)vname[1])) {
1477                         if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1478                             (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1479                             (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1480                             (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1481                                 value = emalloc(consumed + 1);
1482                                 strncpy(value, vp->input, consumed);
1483                                 value[consumed] = '\0';
1484
1485                                 *freeResult = TRUE;
1486                                 return (value);
1487                         }
1488                 }
1489         } else {
1490                 /*
1491                  * Check for D and F forms of local variables since we're in
1492                  * a local context and the name is the right length.
1493                  */
1494                 if (vlen == 2 &&
1495                     (vname[1] == 'F' || vname[1] == 'D') &&
1496                     (strchr("!%*<>@", vname[0]) != NULL)) {
1497                         char    name[2];
1498
1499                         name[0] = vname[0];
1500                         name[1] = '\0';
1501
1502                         v = VarFindOnly(name, vp->ctxt);
1503                         if (v != NULL) {
1504                                 char    *val;
1505                                 /*
1506                                  * No need for nested expansion or anything,
1507                                  * as we're the only one who sets these
1508                                  * things and we sure don't put nested
1509                                  * invocations in them...
1510                                  */
1511                                 val = Buf_Data(v->val);
1512
1513                                 if (vname[1] == 'D') {
1514                                         val = VarModify(val, VarHead, NULL);
1515                                 } else {
1516                                         val = VarModify(val, VarTail, NULL);
1517                                 }
1518
1519                                 *freeResult = TRUE;
1520                                 return (val);
1521                         }
1522                 }
1523         }
1524
1525         *freeResult = FALSE;
1526         return (vp->err ? var_Error : varNoError);
1527 }
1528
1529 /**
1530  * Parse a multi letter variable name, and return it's value.
1531  */
1532 static char *
1533 VarParseLong(VarParser *vp, Boolean *freeResult)
1534 {
1535         Buffer          *buf;
1536         char            startc;
1537         char            endc;
1538         char            *value;
1539
1540         buf = Buf_Init(MAKE_BSIZE);
1541
1542         startc = vp->ptr[0];
1543         vp->ptr++;              /* consume opening paren or brace */
1544
1545         endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1546
1547         /*
1548          * Process characters until we reach an end character or a colon,
1549          * replacing embedded variables as we go.
1550          */
1551         while (*vp->ptr != '\0') {
1552                 if (*vp->ptr == endc) {
1553                         value = ParseRestEnd(vp, buf, freeResult);
1554                         vp->ptr++;      /* consume closing paren or brace */
1555                         Buf_Destroy(buf, TRUE);
1556                         return (value);
1557
1558                 } else if (*vp->ptr == ':') {
1559                         value = ParseRestModifier(vp, startc, buf, freeResult);
1560                         vp->ptr++;      /* consume closing paren or brace */
1561                         Buf_Destroy(buf, TRUE);
1562                         return (value);
1563
1564                 } else if (*vp->ptr == '$') {
1565                         VarParser       subvp = {
1566                                 vp->ptr,
1567                                 vp->ptr,
1568                                 vp->ctxt,
1569                                 vp->err
1570                         };
1571                         char    *rval;
1572                         Boolean rfree;
1573
1574                         rval = VarParse(&subvp, &rfree);
1575                         if (rval == var_Error) {
1576                                 Fatal("Error expanding embedded variable.");
1577                         }
1578                         Buf_Append(buf, rval);
1579                         if (rfree)
1580                                 free(rval);
1581                         vp->ptr = subvp.ptr;
1582                 } else {
1583                         Buf_AddByte(buf, (Byte)*vp->ptr);
1584                         vp->ptr++;
1585                 }
1586         }
1587
1588         /* If we did not find the end character, return var_Error */
1589         Buf_Destroy(buf, TRUE);
1590         *freeResult = FALSE;
1591         return (var_Error);
1592 }
1593
1594 /**
1595  * Parse a single letter variable name, and return it's value.
1596  */
1597 static char *
1598 VarParseShort(VarParser *vp, Boolean *freeResult)
1599 {
1600         char    vname[2];
1601         Var     *v;
1602         char    *value;
1603
1604         vname[0] = vp->ptr[0];
1605         vname[1] = '\0';
1606
1607         vp->ptr++;      /* consume single letter */
1608
1609         v = VarFindAny(vname, vp->ctxt);
1610         if (v != NULL) {
1611                 value = VarExpand(v, vp);
1612
1613                 if (v->flags & VAR_FROM_ENV) {
1614                         VarDestroy(v, TRUE);
1615                 }
1616
1617                 *freeResult = TRUE;
1618                 return (value);
1619         }
1620
1621         /*
1622          * If substituting a local variable in a non-local context, assume
1623          * it's for dynamic source stuff. We have to handle this specially
1624          * and return the longhand for the variable with the dollar sign
1625          * escaped so it makes it back to the caller. Only four of the local
1626          * variables are treated specially as they are the only four that
1627          * will be set when dynamic sources are expanded.
1628          */
1629         if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1630
1631                 /* XXX: It looks like $% and $! are reversed here */
1632                 switch (vname[0]) {
1633                 case '@':
1634                         *freeResult = TRUE;
1635                         return (estrdup("$(.TARGET)"));
1636                 case '%':
1637                         *freeResult = TRUE;
1638                         return (estrdup("$(.ARCHIVE)"));
1639                 case '*':
1640                         *freeResult = TRUE;
1641                         return (estrdup("$(.PREFIX)"));
1642                 case '!':
1643                         *freeResult = TRUE;
1644                         return (estrdup("$(.MEMBER)"));
1645                 default:
1646                         *freeResult = FALSE;
1647                         return (vp->err ? var_Error : varNoError);
1648                 }
1649         }
1650
1651         /* Variable name was not found. */
1652         *freeResult = FALSE;
1653         return (vp->err ? var_Error : varNoError);
1654 }
1655
1656 static char *
1657 VarParse(VarParser *vp, Boolean *freeResult)
1658 {
1659
1660         vp->ptr++;      /* consume '$' or last letter of conditional */
1661
1662         if (vp->ptr[0] == '\0') {
1663                 /* Error, there is only a dollar sign in the input string. */
1664                 *freeResult = FALSE;
1665                 return (vp->err ? var_Error : varNoError);
1666
1667         } else if (vp->ptr[0] == OPEN_PAREN || vp->ptr[0] == OPEN_BRACE) {
1668                 /* multi letter variable name */
1669                 return (VarParseLong(vp, freeResult));
1670
1671         } else {
1672                 /* single letter variable name */
1673                 return (VarParseShort(vp, freeResult));
1674         }
1675 }
1676
1677 /*-
1678  *-----------------------------------------------------------------------
1679  * Var_Parse --
1680  *      Given the start of a variable invocation, extract the variable
1681  *      name and find its value, then modify it according to the
1682  *      specification.
1683  *
1684  * Results:
1685  *      The value of the variable or var_Error if the specification
1686  *      is invalid.  The number of characters in the specification
1687  *      is placed in the variable pointed to by consumed.  (for
1688  *      invalid specifications, this is just 2 to skip the '$' and
1689  *      the following letter, or 1 if '$' was the last character
1690  *      in the string).  A Boolean in *freeResult telling whether the
1691  *      returned string should be freed by the caller.
1692  *
1693  * Side Effects:
1694  *      None.
1695  *-----------------------------------------------------------------------
1696  */
1697 char *
1698 Var_Parse(const char input[], GNode *ctxt, Boolean err,
1699         size_t *consumed, Boolean *freeResult)
1700 {
1701         VarParser       vp = {
1702                 input,
1703                 input,
1704                 ctxt,
1705                 err
1706         };
1707         char            *value;
1708
1709         value = VarParse(&vp, freeResult);
1710         *consumed += vp.ptr - vp.input;
1711         return (value);
1712 }
1713
1714 /*-
1715  *-----------------------------------------------------------------------
1716  * Var_Subst  --
1717  *      Substitute for all variables in the given string in the given context
1718  *      If err is TRUE, Parse_Error will be called when an undefined
1719  *      variable is encountered.
1720  *
1721  * Results:
1722  *      The resulting string.
1723  *
1724  * Side Effects:
1725  *      None. The old string must be freed by the caller
1726  *-----------------------------------------------------------------------
1727  */
1728 Buffer *
1729 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean err)
1730 {
1731         Boolean errorReported;
1732         Buffer *buf;            /* Buffer for forming things */
1733
1734         /*
1735          * Set TRUE if an error has already been reported to prevent a
1736          * plethora of messages when recursing. XXXHB this comment sounds
1737          * wrong.
1738          */
1739         errorReported = FALSE;
1740
1741         buf = Buf_Init(0);
1742         while (*str) {
1743                 if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1744                         /*
1745                          * A dollar sign may be escaped either with another
1746                          * dollar sign. In such a case, we skip over the
1747                          * escape character and store the dollar sign into
1748                          * the buffer directly.
1749                          */
1750                         Buf_AddByte(buf, (Byte)str[0]);
1751                         str += 2;
1752
1753                 } else if (str[0] == '$') {
1754                         /*
1755                          * Variable invocation.
1756                          */
1757                         if (var != NULL) {
1758                                 int     expand;
1759                                 for (;;) {
1760                                         if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACE) {
1761                                                 size_t  ln;
1762                                                 const char *p = str + 2;
1763
1764                                                 /*
1765                                                  * Scan up to the end of the
1766                                                  * variable name.
1767                                                  */
1768                                                 while (*p != '\0' &&
1769                                                        *p != ':' &&
1770                                                        *p != CLOSE_PAREN &&
1771                                                        *p != CLOSE_BRACE &&
1772                                                        *p != '$') {
1773                                                         ++p;
1774                                                 }
1775
1776                                                 /*
1777                                                  * A variable inside the
1778                                                  * variable. We cannot expand
1779                                                  * the external variable yet,
1780                                                  * so we try again with the
1781                                                  * nested one
1782                                                  */
1783                                                 if (*p == '$') {
1784                                                         Buf_AppendRange(buf, str, p);
1785                                                         str = p;
1786                                                         continue;
1787                                                 }
1788                                                 ln = p - (str + 2);
1789                                                 if (var[ln] == '\0' && strncmp(var, str + 2, ln) == 0) {
1790                                                         expand = TRUE;
1791                                                 } else {
1792                                                         /*
1793                                                          * Not the variable
1794                                                          * we want to expand,
1795                                                          * scan until the
1796                                                          * next variable
1797                                                          */
1798                                                         while (*p != '$' && *p != '\0')
1799                                                                 p++;
1800
1801                                                         Buf_AppendRange(buf, str, p);
1802                                                         str = p;
1803                                                         expand = FALSE;
1804                                                 }
1805                                         } else {
1806                                                 /*
1807                                                  * Single letter variable
1808                                                  * name
1809                                                  */
1810                                                 if (var[1] == '\0' && var[0] == str[1]) {
1811                                                         expand = TRUE;
1812                                                 } else {
1813                                                         Buf_AddBytes(buf, 2, (const Byte *) str);
1814                                                         str += 2;
1815                                                         expand = FALSE;
1816                                                 }
1817                                         }
1818                                         break;
1819                                 }
1820                                 if (!expand)
1821                                         continue;
1822                         }
1823                     {
1824                         VarParser       subvp = {
1825                                 str,
1826                                 str,
1827                                 ctxt,
1828                                 err
1829                         };
1830                         char    *rval;
1831                         Boolean rfree;
1832
1833                         rval = VarParse(&subvp, &rfree);
1834
1835                         /*
1836                          * When we come down here, val should either point to
1837                          * the value of this variable, suitably modified, or
1838                          * be NULL. Length should be the total length of the
1839                          * potential variable invocation (from $ to end
1840                          * character...)
1841                          */
1842                         if (rval == var_Error || rval == varNoError) {
1843                                 /*
1844                                  * If performing old-time variable
1845                                  * substitution, skip over the variable and
1846                                  * continue with the substitution. Otherwise,
1847                                  * store the dollar sign and advance str so
1848                                  * we continue with the string...
1849                                  */
1850                                 if (oldVars) {
1851                                         str = subvp.ptr;
1852                                 } else if (err) {
1853                                         /*
1854                                          * If variable is undefined, complain
1855                                          * and skip the variable. The
1856                                          * complaint will stop us from doing
1857                                          * anything when the file is parsed.
1858                                          */
1859                                         if (!errorReported) {
1860                                                 Parse_Error(PARSE_FATAL,
1861                                                             "Undefined variable \"%.*s\"", subvp.ptr - subvp.input, str);
1862                                         }
1863                                         str = subvp.ptr;
1864                                         errorReported = TRUE;
1865                                 } else {
1866                                         Buf_AddByte(buf, (Byte)*str);
1867                                         str += 1;
1868                                 }
1869                         } else {
1870                                 /*
1871                                  * We've now got a variable structure to
1872                                  * store in. But first, advance the string
1873                                  * pointer.
1874                                  */
1875                                 str = subvp.ptr;
1876
1877                                 /*
1878                                  * Copy all the characters from the variable
1879                                  * value straight into the new string.
1880                                  */
1881                                 Buf_Append(buf, rval);
1882                                 if (rfree) {
1883                                         free(rval);
1884                                 }
1885                         }
1886                     }
1887                 } else {
1888                         /*
1889                          * Skip as many characters as possible -- either to
1890                          * the end of the string or to the next dollar sign
1891                          * (variable invocation).
1892                          */
1893                         const char *cp = str;
1894
1895                         do {
1896                                 str++;
1897                         } while (str[0] != '$' && str[0] != '\0');
1898
1899                         Buf_AppendRange(buf, cp, str);
1900                 }
1901         }
1902
1903         return (buf);
1904 }
1905
1906 /*-
1907  *-----------------------------------------------------------------------
1908  * Var_GetTail --
1909  *      Return the tail from each of a list of words. Used to set the
1910  *      System V local variables.
1911  *
1912  * Results:
1913  *      The resulting string.
1914  *
1915  * Side Effects:
1916  *      None.
1917  *
1918  *-----------------------------------------------------------------------
1919  */
1920 char *
1921 Var_GetTail(char *file)
1922 {
1923
1924         return (VarModify(file, VarTail, (void *)NULL));
1925 }
1926
1927 /*-
1928  *-----------------------------------------------------------------------
1929  * Var_GetHead --
1930  *      Find the leading components of a (list of) filename(s).
1931  *      XXX: VarHead does not replace foo by ., as (sun) System V make
1932  *      does.
1933  *
1934  * Results:
1935  *      The leading components.
1936  *
1937  * Side Effects:
1938  *      None.
1939  *
1940  *-----------------------------------------------------------------------
1941  */
1942 char *
1943 Var_GetHead(char *file)
1944 {
1945
1946         return (VarModify(file, VarHead, (void *)NULL));
1947 }
1948
1949 /*-
1950  *-----------------------------------------------------------------------
1951  * Var_Init --
1952  *      Initialize the module
1953  *
1954  * Results:
1955  *      None
1956  *
1957  * Side Effects:
1958  *      The VAR_CMD and VAR_GLOBAL contexts are created
1959  *-----------------------------------------------------------------------
1960  */
1961 void
1962 Var_Init(void)
1963 {
1964
1965         VAR_GLOBAL = Targ_NewGN("Global");
1966         VAR_CMD = Targ_NewGN("Command");
1967 }
1968
1969 /*-
1970  *-----------------------------------------------------------------------
1971  * Var_Dump --
1972  *      print all variables in a context
1973  *-----------------------------------------------------------------------
1974  */
1975 void
1976 Var_Dump(const GNode *ctxt)
1977 {
1978         const LstNode   *ln;
1979         const Var       *v;
1980
1981         LST_FOREACH(ln, &ctxt->context) {
1982                 v = Lst_Datum(ln);
1983                 printf("%-16s = %s\n", v->name, Buf_Data(v->val));
1984         }
1985 }