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