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