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