VirtualBox

source: kBuild/trunk/src/kmk/var.c@ 30

Last change on this file since 30 was 30, checked in by bird, 22 years ago

Basic nmake emulation.

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette