cond.c revision 1.6.6.1 1 /* $NetBSD: cond.c,v 1.6.6.1 1997/01/26 05:51:33 rat Exp $ */
2
3 /*
4 * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
5 * Copyright (c) 1988, 1989 by Adam de Boor
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 #ifndef lint
42 #if 0
43 static char sccsid[] = "@(#)cond.c 8.2 (Berkeley) 1/2/94";
44 #else
45 static char rcsid[] = "$NetBSD: cond.c,v 1.6.6.1 1997/01/26 05:51:33 rat Exp $";
46 #endif
47 #endif /* not lint */
48
49 /*-
50 * cond.c --
51 * Functions to handle conditionals in a makefile.
52 *
53 * Interface:
54 * Cond_Eval Evaluate the conditional in the passed line.
55 *
56 */
57
58 #include <ctype.h>
59 #include <math.h>
60 #include "make.h"
61 #include "hash.h"
62 #include "dir.h"
63 #include "buf.h"
64
65 /*
66 * The parsing of conditional expressions is based on this grammar:
67 * E -> F || E
68 * E -> F
69 * F -> T && F
70 * F -> T
71 * T -> defined(variable)
72 * T -> make(target)
73 * T -> exists(file)
74 * T -> empty(varspec)
75 * T -> target(name)
76 * T -> symbol
77 * T -> $(varspec) op value
78 * T -> $(varspec) == "string"
79 * T -> $(varspec) != "string"
80 * T -> ( E )
81 * T -> ! T
82 * op -> == | != | > | < | >= | <=
83 *
84 * 'symbol' is some other symbol to which the default function (condDefProc)
85 * is applied.
86 *
87 * Tokens are scanned from the 'condExpr' string. The scanner (CondToken)
88 * will return And for '&' and '&&', Or for '|' and '||', Not for '!',
89 * LParen for '(', RParen for ')' and will evaluate the other terminal
90 * symbols, using either the default function or the function given in the
91 * terminal, and return the result as either True or False.
92 *
93 * All Non-Terminal functions (CondE, CondF and CondT) return Err on error.
94 */
95 typedef enum {
96 And, Or, Not, True, False, LParen, RParen, EndOfFile, None, Err
97 } Token;
98
99 /*-
100 * Structures to handle elegantly the different forms of #if's. The
101 * last two fields are stored in condInvert and condDefProc, respectively.
102 */
103 static void CondPushBack __P((Token));
104 static int CondGetArg __P((char **, char **, char *, Boolean));
105 static Boolean CondDoDefined __P((int, char *));
106 static int CondStrMatch __P((ClientData, ClientData));
107 static Boolean CondDoMake __P((int, char *));
108 static Boolean CondDoExists __P((int, char *));
109 static Boolean CondDoTarget __P((int, char *));
110 static Boolean CondCvtArg __P((char *, double *));
111 static Token CondToken __P((Boolean));
112 static Token CondT __P((Boolean));
113 static Token CondF __P((Boolean));
114 static Token CondE __P((Boolean));
115
116 static struct If {
117 char *form; /* Form of if */
118 int formlen; /* Length of form */
119 Boolean doNot; /* TRUE if default function should be negated */
120 Boolean (*defProc) __P((int, char *)); /* Default function to apply */
121 } ifs[] = {
122 { "ifdef", 5, FALSE, CondDoDefined },
123 { "ifndef", 6, TRUE, CondDoDefined },
124 { "ifmake", 6, FALSE, CondDoMake },
125 { "ifnmake", 7, TRUE, CondDoMake },
126 { "if", 2, FALSE, CondDoDefined },
127 { NULL, 0, FALSE, NULL }
128 };
129
130 static Boolean condInvert; /* Invert the default function */
131 static Boolean (*condDefProc) /* Default function to apply */
132 __P((int, char *));
133 static char *condExpr; /* The expression to parse */
134 static Token condPushBack=None; /* Single push-back token used in
135 * parsing */
136
137 #define MAXIF 30 /* greatest depth of #if'ing */
138
139 static Boolean condStack[MAXIF]; /* Stack of conditionals's values */
140 static int condTop = MAXIF; /* Top-most conditional */
141 static int skipIfLevel=0; /* Depth of skipped conditionals */
142 static Boolean skipLine = FALSE; /* Whether the parse module is skipping
143 * lines */
144
145 /*-
146 *-----------------------------------------------------------------------
147 * CondPushBack --
148 * Push back the most recent token read. We only need one level of
149 * this, so the thing is just stored in 'condPushback'.
150 *
151 * Results:
152 * None.
153 *
154 * Side Effects:
155 * condPushback is overwritten.
156 *
157 *-----------------------------------------------------------------------
158 */
159 static void
160 CondPushBack (t)
161 Token t; /* Token to push back into the "stream" */
162 {
163 condPushBack = t;
164 }
165
166 /*-
168 *-----------------------------------------------------------------------
169 * CondGetArg --
170 * Find the argument of a built-in function.
171 *
172 * Results:
173 * The length of the argument and the address of the argument.
174 *
175 * Side Effects:
176 * The pointer is set to point to the closing parenthesis of the
177 * function call.
178 *
179 *-----------------------------------------------------------------------
180 */
181 static int
182 CondGetArg (linePtr, argPtr, func, parens)
183 char **linePtr;
184 char **argPtr;
185 char *func;
186 Boolean parens; /* TRUE if arg should be bounded by parens */
187 {
188 register char *cp;
189 int argLen;
190 register Buffer buf;
191
192 cp = *linePtr;
193 if (parens) {
194 while (*cp != '(' && *cp != '\0') {
195 cp++;
196 }
197 if (*cp == '(') {
198 cp++;
199 }
200 }
201
202 if (*cp == '\0') {
203 /*
204 * No arguments whatsoever. Because 'make' and 'defined' aren't really
205 * "reserved words", we don't print a message. I think this is better
206 * than hitting the user with a warning message every time s/he uses
207 * the word 'make' or 'defined' at the beginning of a symbol...
208 */
209 *argPtr = cp;
210 return (0);
211 }
212
213 while (*cp == ' ' || *cp == '\t') {
214 cp++;
215 }
216
217 /*
218 * Create a buffer for the argument and start it out at 16 characters
219 * long. Why 16? Why not?
220 */
221 buf = Buf_Init(16);
222
223 while ((strchr(" \t)&|", *cp) == (char *)NULL) && (*cp != '\0')) {
224 if (*cp == '$') {
225 /*
226 * Parse the variable spec and install it as part of the argument
227 * if it's valid. We tell Var_Parse to complain on an undefined
228 * variable, so we don't do it too. Nor do we return an error,
229 * though perhaps we should...
230 */
231 char *cp2;
232 int len;
233 Boolean doFree;
234
235 cp2 = Var_Parse(cp, VAR_CMD, TRUE, &len, &doFree);
236
237 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
238 if (doFree) {
239 free(cp2);
240 }
241 cp += len;
242 } else {
243 Buf_AddByte(buf, (Byte)*cp);
244 cp++;
245 }
246 }
247
248 Buf_AddByte(buf, (Byte)'\0');
249 *argPtr = (char *)Buf_GetAll(buf, &argLen);
250 Buf_Destroy(buf, FALSE);
251
252 while (*cp == ' ' || *cp == '\t') {
253 cp++;
254 }
255 if (parens && *cp != ')') {
256 Parse_Error (PARSE_WARNING, "Missing closing parenthesis for %s()",
257 func);
258 return (0);
259 } else if (parens) {
260 /*
261 * Advance pointer past close parenthesis.
262 */
263 cp++;
264 }
265
266 *linePtr = cp;
267 return (argLen);
268 }
269
270 /*-
272 *-----------------------------------------------------------------------
273 * CondDoDefined --
274 * Handle the 'defined' function for conditionals.
275 *
276 * Results:
277 * TRUE if the given variable is defined.
278 *
279 * Side Effects:
280 * None.
281 *
282 *-----------------------------------------------------------------------
283 */
284 static Boolean
285 CondDoDefined (argLen, arg)
286 int argLen;
287 char *arg;
288 {
289 char savec = arg[argLen];
290 char *p1;
291 Boolean result;
292
293 arg[argLen] = '\0';
294 if (Var_Value (arg, VAR_CMD, &p1) != (char *)NULL) {
295 result = TRUE;
296 } else {
297 result = FALSE;
298 }
299 if (p1)
300 free(p1);
301 arg[argLen] = savec;
302 return (result);
303 }
304
305 /*-
307 *-----------------------------------------------------------------------
308 * CondStrMatch --
309 * Front-end for Str_Match so it returns 0 on match and non-zero
310 * on mismatch. Callback function for CondDoMake via Lst_Find
311 *
312 * Results:
313 * 0 if string matches pattern
314 *
315 * Side Effects:
316 * None
317 *
318 *-----------------------------------------------------------------------
319 */
320 static int
321 CondStrMatch(string, pattern)
322 ClientData string;
323 ClientData pattern;
324 {
325 return(!Str_Match((char *) string,(char *) pattern));
326 }
327
328 /*-
330 *-----------------------------------------------------------------------
331 * CondDoMake --
332 * Handle the 'make' function for conditionals.
333 *
334 * Results:
335 * TRUE if the given target is being made.
336 *
337 * Side Effects:
338 * None.
339 *
340 *-----------------------------------------------------------------------
341 */
342 static Boolean
343 CondDoMake (argLen, arg)
344 int argLen;
345 char *arg;
346 {
347 char savec = arg[argLen];
348 Boolean result;
349
350 arg[argLen] = '\0';
351 if (Lst_Find (create, (ClientData)arg, CondStrMatch) == NILLNODE) {
352 result = FALSE;
353 } else {
354 result = TRUE;
355 }
356 arg[argLen] = savec;
357 return (result);
358 }
359
360 /*-
362 *-----------------------------------------------------------------------
363 * CondDoExists --
364 * See if the given file exists.
365 *
366 * Results:
367 * TRUE if the file exists and FALSE if it does not.
368 *
369 * Side Effects:
370 * None.
371 *
372 *-----------------------------------------------------------------------
373 */
374 static Boolean
375 CondDoExists (argLen, arg)
376 int argLen;
377 char *arg;
378 {
379 char savec = arg[argLen];
380 Boolean result;
381 char *path;
382
383 arg[argLen] = '\0';
384 path = Dir_FindFile(arg, dirSearchPath);
385 if (path != (char *)NULL) {
386 result = TRUE;
387 free(path);
388 } else {
389 result = FALSE;
390 }
391 arg[argLen] = savec;
392 return (result);
393 }
394
395 /*-
397 *-----------------------------------------------------------------------
398 * CondDoTarget --
399 * See if the given node exists and is an actual target.
400 *
401 * Results:
402 * TRUE if the node exists as a target and FALSE if it does not.
403 *
404 * Side Effects:
405 * None.
406 *
407 *-----------------------------------------------------------------------
408 */
409 static Boolean
410 CondDoTarget (argLen, arg)
411 int argLen;
412 char *arg;
413 {
414 char savec = arg[argLen];
415 Boolean result;
416 GNode *gn;
417
418 arg[argLen] = '\0';
419 gn = Targ_FindNode(arg, TARG_NOCREATE);
420 if ((gn != NILGNODE) && !OP_NOP(gn->type)) {
421 result = TRUE;
422 } else {
423 result = FALSE;
424 }
425 arg[argLen] = savec;
426 return (result);
427 }
428
429
430 /*-
432 *-----------------------------------------------------------------------
433 * CondCvtArg --
434 * Convert the given number into a double. If the number begins
435 * with 0x, it is interpreted as a hexadecimal integer
436 * and converted to a double from there. All other strings just have
437 * strtod called on them.
438 *
439 * Results:
440 * Sets 'value' to double value of string.
441 * Returns true if the string was a valid number, false o.w.
442 *
443 * Side Effects:
444 * Can change 'value' even if string is not a valid number.
445 *
446 *
447 *-----------------------------------------------------------------------
448 */
449 static Boolean
450 CondCvtArg(str, value)
451 register char *str;
452 double *value;
453 {
454 if ((*str == '0') && (str[1] == 'x')) {
455 register long i;
456
457 for (str += 2, i = 0; *str; str++) {
458 int x;
459 if (isdigit((unsigned char) *str))
460 x = *str - '0';
461 else if (isxdigit((unsigned char) *str))
462 x = 10 + *str - isupper((unsigned char) *str) ? 'A' : 'a';
463 else
464 return FALSE;
465 i = (i << 4) + x;
466 }
467 *value = (double) i;
468 return TRUE;
469 }
470 else {
471 char *eptr;
472 *value = strtod(str, &eptr);
473 return *eptr == '\0';
474 }
475 }
476
477 /*-
479 *-----------------------------------------------------------------------
480 * CondToken --
481 * Return the next token from the input.
482 *
483 * Results:
484 * A Token for the next lexical token in the stream.
485 *
486 * Side Effects:
487 * condPushback will be set back to None if it is used.
488 *
489 *-----------------------------------------------------------------------
490 */
491 static Token
492 CondToken(doEval)
493 Boolean doEval;
494 {
495 Token t;
496
497 if (condPushBack == None) {
498 while (*condExpr == ' ' || *condExpr == '\t') {
499 condExpr++;
500 }
501 switch (*condExpr) {
502 case '(':
503 t = LParen;
504 condExpr++;
505 break;
506 case ')':
507 t = RParen;
508 condExpr++;
509 break;
510 case '|':
511 if (condExpr[1] == '|') {
512 condExpr++;
513 }
514 condExpr++;
515 t = Or;
516 break;
517 case '&':
518 if (condExpr[1] == '&') {
519 condExpr++;
520 }
521 condExpr++;
522 t = And;
523 break;
524 case '!':
525 t = Not;
526 condExpr++;
527 break;
528 case '\n':
529 case '\0':
530 t = EndOfFile;
531 break;
532 case '$': {
533 char *lhs;
534 char *rhs;
535 char *op;
536 int varSpecLen;
537 Boolean doFree;
538
539 /*
540 * Parse the variable spec and skip over it, saving its
541 * value in lhs.
542 */
543 t = Err;
544 lhs = Var_Parse(condExpr, VAR_CMD, doEval,&varSpecLen,&doFree);
545 if (lhs == var_Error) {
546 /*
547 * Even if !doEval, we still report syntax errors, which
548 * is what getting var_Error back with !doEval means.
549 */
550 return(Err);
551 }
552 condExpr += varSpecLen;
553
554 if (!isspace((unsigned char) *condExpr) &&
555 strchr("!=><", *condExpr) == NULL) {
556 Buffer buf;
557 char *cp;
558
559 buf = Buf_Init(0);
560
561 for (cp = lhs; *cp; cp++)
562 Buf_AddByte(buf, (Byte)*cp);
563
564 if (doFree)
565 free(lhs);
566
567 for (;*condExpr && !isspace((unsigned char) *condExpr);
568 condExpr++)
569 Buf_AddByte(buf, (Byte)*condExpr);
570
571 Buf_AddByte(buf, (Byte)'\0');
572 lhs = (char *)Buf_GetAll(buf, &varSpecLen);
573 Buf_Destroy(buf, FALSE);
574
575 doFree = TRUE;
576 }
577
578 /*
579 * Skip whitespace to get to the operator
580 */
581 while (isspace((unsigned char) *condExpr))
582 condExpr++;
583
584 /*
585 * Make sure the operator is a valid one. If it isn't a
586 * known relational operator, pretend we got a
587 * != 0 comparison.
588 */
589 op = condExpr;
590 switch (*condExpr) {
591 case '!':
592 case '=':
593 case '<':
594 case '>':
595 if (condExpr[1] == '=') {
596 condExpr += 2;
597 } else {
598 condExpr += 1;
599 }
600 break;
601 default:
602 op = "!=";
603 rhs = "0";
604
605 goto do_compare;
606 }
607 while (isspace((unsigned char) *condExpr)) {
608 condExpr++;
609 }
610 if (*condExpr == '\0') {
611 Parse_Error(PARSE_WARNING,
612 "Missing right-hand-side of operator");
613 goto error;
614 }
615 rhs = condExpr;
616 do_compare:
617 if (*rhs == '"') {
618 /*
619 * Doing a string comparison. Only allow == and != for
620 * operators.
621 */
622 char *string;
623 char *cp, *cp2;
624 int qt;
625 Buffer buf;
626
627 do_string_compare:
628 if (((*op != '!') && (*op != '=')) || (op[1] != '=')) {
629 Parse_Error(PARSE_WARNING,
630 "String comparison operator should be either == or !=");
631 goto error;
632 }
633
634 buf = Buf_Init(0);
635 qt = *rhs == '"' ? 1 : 0;
636
637 for (cp = &rhs[qt];
638 ((qt && (*cp != '"')) ||
639 (!qt && strchr(" \t)", *cp) == NULL)) &&
640 (*cp != '\0'); cp++) {
641 if ((*cp == '\\') && (cp[1] != '\0')) {
642 /*
643 * Backslash escapes things -- skip over next
644 * character, if it exists.
645 */
646 cp++;
647 Buf_AddByte(buf, (Byte)*cp);
648 } else if (*cp == '$') {
649 int len;
650 Boolean freeIt;
651
652 cp2 = Var_Parse(cp, VAR_CMD, doEval,&len, &freeIt);
653 if (cp2 != var_Error) {
654 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
655 if (freeIt) {
656 free(cp2);
657 }
658 cp += len - 1;
659 } else {
660 Buf_AddByte(buf, (Byte)*cp);
661 }
662 } else {
663 Buf_AddByte(buf, (Byte)*cp);
664 }
665 }
666
667 Buf_AddByte(buf, (Byte)0);
668
669 string = (char *)Buf_GetAll(buf, (int *)0);
670 Buf_Destroy(buf, FALSE);
671
672 if (DEBUG(COND)) {
673 printf("lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
674 lhs, string, op);
675 }
676 /*
677 * Null-terminate rhs and perform the comparison.
678 * t is set to the result.
679 */
680 if (*op == '=') {
681 t = strcmp(lhs, string) ? False : True;
682 } else {
683 t = strcmp(lhs, string) ? True : False;
684 }
685 free(string);
686 if (rhs == condExpr) {
687 if (!qt && *cp == ')')
688 condExpr = cp;
689 else
690 condExpr = cp + 1;
691 }
692 } else {
693 /*
694 * rhs is either a float or an integer. Convert both the
695 * lhs and the rhs to a double and compare the two.
696 */
697 double left, right;
698 char *string;
699
700 if (!CondCvtArg(lhs, &left))
701 goto do_string_compare;
702 if (*rhs == '$') {
703 int len;
704 Boolean freeIt;
705
706 string = Var_Parse(rhs, VAR_CMD, doEval,&len,&freeIt);
707 if (string == var_Error) {
708 right = 0.0;
709 } else {
710 if (!CondCvtArg(string, &right)) {
711 if (freeIt)
712 free(string);
713 goto do_string_compare;
714 }
715 if (freeIt)
716 free(string);
717 if (rhs == condExpr)
718 condExpr += len;
719 }
720 } else {
721 if (!CondCvtArg(rhs, &right))
722 goto do_string_compare;
723 if (rhs == condExpr) {
724 /*
725 * Skip over the right-hand side
726 */
727 while(!isspace((unsigned char) *condExpr) &&
728 (*condExpr != '\0')) {
729 condExpr++;
730 }
731 }
732 }
733
734 if (DEBUG(COND)) {
735 printf("left = %f, right = %f, op = %.2s\n", left,
736 right, op);
737 }
738 switch(op[0]) {
739 case '!':
740 if (op[1] != '=') {
741 Parse_Error(PARSE_WARNING,
742 "Unknown operator");
743 goto error;
744 }
745 t = (left != right ? True : False);
746 break;
747 case '=':
748 if (op[1] != '=') {
749 Parse_Error(PARSE_WARNING,
750 "Unknown operator");
751 goto error;
752 }
753 t = (left == right ? True : False);
754 break;
755 case '<':
756 if (op[1] == '=') {
757 t = (left <= right ? True : False);
758 } else {
759 t = (left < right ? True : False);
760 }
761 break;
762 case '>':
763 if (op[1] == '=') {
764 t = (left >= right ? True : False);
765 } else {
766 t = (left > right ? True : False);
767 }
768 break;
769 }
770 }
771 error:
772 if (doFree)
773 free(lhs);
774 break;
775 }
776 default: {
777 Boolean (*evalProc) __P((int, char *));
778 Boolean invert = FALSE;
779 char *arg;
780 int arglen;
781
782 if (strncmp (condExpr, "defined", 7) == 0) {
783 /*
784 * Use CondDoDefined to evaluate the argument and
785 * CondGetArg to extract the argument from the 'function
786 * call'.
787 */
788 evalProc = CondDoDefined;
789 condExpr += 7;
790 arglen = CondGetArg (&condExpr, &arg, "defined", TRUE);
791 if (arglen == 0) {
792 condExpr -= 7;
793 goto use_default;
794 }
795 } else if (strncmp (condExpr, "make", 4) == 0) {
796 /*
797 * Use CondDoMake to evaluate the argument and
798 * CondGetArg to extract the argument from the 'function
799 * call'.
800 */
801 evalProc = CondDoMake;
802 condExpr += 4;
803 arglen = CondGetArg (&condExpr, &arg, "make", TRUE);
804 if (arglen == 0) {
805 condExpr -= 4;
806 goto use_default;
807 }
808 } else if (strncmp (condExpr, "exists", 6) == 0) {
809 /*
810 * Use CondDoExists to evaluate the argument and
811 * CondGetArg to extract the argument from the
812 * 'function call'.
813 */
814 evalProc = CondDoExists;
815 condExpr += 6;
816 arglen = CondGetArg(&condExpr, &arg, "exists", TRUE);
817 if (arglen == 0) {
818 condExpr -= 6;
819 goto use_default;
820 }
821 } else if (strncmp(condExpr, "empty", 5) == 0) {
822 /*
823 * Use Var_Parse to parse the spec in parens and return
824 * True if the resulting string is empty.
825 */
826 int length;
827 Boolean doFree;
828 char *val;
829
830 condExpr += 5;
831
832 for (arglen = 0;
833 condExpr[arglen] != '(' && condExpr[arglen] != '\0';
834 arglen += 1)
835 continue;
836
837 if (condExpr[arglen] != '\0') {
838 val = Var_Parse(&condExpr[arglen - 1], VAR_CMD,
839 doEval, &length, &doFree);
840 if (val == var_Error) {
841 t = Err;
842 } else {
843 /*
844 * A variable is empty when it just contains
845 * spaces... 4/15/92, christos
846 */
847 char *p;
848 for (p = val; *p && isspace((unsigned char)*p); p++)
849 continue;
850 t = (*p == '\0') ? True : False;
851 }
852 if (doFree) {
853 free(val);
854 }
855 /*
856 * Advance condExpr to beyond the closing ). Note that
857 * we subtract one from arglen + length b/c length
858 * is calculated from condExpr[arglen - 1].
859 */
860 condExpr += arglen + length - 1;
861 } else {
862 condExpr -= 5;
863 goto use_default;
864 }
865 break;
866 } else if (strncmp (condExpr, "target", 6) == 0) {
867 /*
868 * Use CondDoTarget to evaluate the argument and
869 * CondGetArg to extract the argument from the
870 * 'function call'.
871 */
872 evalProc = CondDoTarget;
873 condExpr += 6;
874 arglen = CondGetArg(&condExpr, &arg, "target", TRUE);
875 if (arglen == 0) {
876 condExpr -= 6;
877 goto use_default;
878 }
879 } else {
880 /*
881 * The symbol is itself the argument to the default
882 * function. We advance condExpr to the end of the symbol
883 * by hand (the next whitespace, closing paren or
884 * binary operator) and set to invert the evaluation
885 * function if condInvert is TRUE.
886 */
887 use_default:
888 invert = condInvert;
889 evalProc = condDefProc;
890 arglen = CondGetArg(&condExpr, &arg, "", FALSE);
891 }
892
893 /*
894 * Evaluate the argument using the set function. If invert
895 * is TRUE, we invert the sense of the function.
896 */
897 t = (!doEval || (* evalProc) (arglen, arg) ?
898 (invert ? False : True) :
899 (invert ? True : False));
900 free(arg);
901 break;
902 }
903 }
904 } else {
905 t = condPushBack;
906 condPushBack = None;
907 }
908 return (t);
909 }
910
911 /*-
913 *-----------------------------------------------------------------------
914 * CondT --
915 * Parse a single term in the expression. This consists of a terminal
916 * symbol or Not and a terminal symbol (not including the binary
917 * operators):
918 * T -> defined(variable) | make(target) | exists(file) | symbol
919 * T -> ! T | ( E )
920 *
921 * Results:
922 * True, False or Err.
923 *
924 * Side Effects:
925 * Tokens are consumed.
926 *
927 *-----------------------------------------------------------------------
928 */
929 static Token
930 CondT(doEval)
931 Boolean doEval;
932 {
933 Token t;
934
935 t = CondToken(doEval);
936
937 if (t == EndOfFile) {
938 /*
939 * If we reached the end of the expression, the expression
940 * is malformed...
941 */
942 t = Err;
943 } else if (t == LParen) {
944 /*
945 * T -> ( E )
946 */
947 t = CondE(doEval);
948 if (t != Err) {
949 if (CondToken(doEval) != RParen) {
950 t = Err;
951 }
952 }
953 } else if (t == Not) {
954 t = CondT(doEval);
955 if (t == True) {
956 t = False;
957 } else if (t == False) {
958 t = True;
959 }
960 }
961 return (t);
962 }
963
964 /*-
966 *-----------------------------------------------------------------------
967 * CondF --
968 * Parse a conjunctive factor (nice name, wot?)
969 * F -> T && F | T
970 *
971 * Results:
972 * True, False or Err
973 *
974 * Side Effects:
975 * Tokens are consumed.
976 *
977 *-----------------------------------------------------------------------
978 */
979 static Token
980 CondF(doEval)
981 Boolean doEval;
982 {
983 Token l, o;
984
985 l = CondT(doEval);
986 if (l != Err) {
987 o = CondToken(doEval);
988
989 if (o == And) {
990 /*
991 * F -> T && F
992 *
993 * If T is False, the whole thing will be False, but we have to
994 * parse the r.h.s. anyway (to throw it away).
995 * If T is True, the result is the r.h.s., be it an Err or no.
996 */
997 if (l == True) {
998 l = CondF(doEval);
999 } else {
1000 (void) CondF(FALSE);
1001 }
1002 } else {
1003 /*
1004 * F -> T
1005 */
1006 CondPushBack (o);
1007 }
1008 }
1009 return (l);
1010 }
1011
1012 /*-
1014 *-----------------------------------------------------------------------
1015 * CondE --
1016 * Main expression production.
1017 * E -> F || E | F
1018 *
1019 * Results:
1020 * True, False or Err.
1021 *
1022 * Side Effects:
1023 * Tokens are, of course, consumed.
1024 *
1025 *-----------------------------------------------------------------------
1026 */
1027 static Token
1028 CondE(doEval)
1029 Boolean doEval;
1030 {
1031 Token l, o;
1032
1033 l = CondF(doEval);
1034 if (l != Err) {
1035 o = CondToken(doEval);
1036
1037 if (o == Or) {
1038 /*
1039 * E -> F || E
1040 *
1041 * A similar thing occurs for ||, except that here we make sure
1042 * the l.h.s. is False before we bother to evaluate the r.h.s.
1043 * Once again, if l is False, the result is the r.h.s. and once
1044 * again if l is True, we parse the r.h.s. to throw it away.
1045 */
1046 if (l == False) {
1047 l = CondE(doEval);
1048 } else {
1049 (void) CondE(FALSE);
1050 }
1051 } else {
1052 /*
1053 * E -> F
1054 */
1055 CondPushBack (o);
1056 }
1057 }
1058 return (l);
1059 }
1060
1061 /*-
1063 *-----------------------------------------------------------------------
1064 * Cond_Eval --
1065 * Evaluate the conditional in the passed line. The line
1066 * looks like this:
1067 * #<cond-type> <expr>
1068 * where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1069 * ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1070 * and <expr> consists of &&, ||, !, make(target), defined(variable)
1071 * and parenthetical groupings thereof.
1072 *
1073 * Results:
1074 * COND_PARSE if should parse lines after the conditional
1075 * COND_SKIP if should skip lines after the conditional
1076 * COND_INVALID if not a valid conditional.
1077 *
1078 * Side Effects:
1079 * None.
1080 *
1081 *-----------------------------------------------------------------------
1082 */
1083 int
1084 Cond_Eval (line)
1085 char *line; /* Line to parse */
1086 {
1087 struct If *ifp;
1088 Boolean isElse;
1089 Boolean value = FALSE;
1090 int level; /* Level at which to report errors. */
1091
1092 level = PARSE_FATAL;
1093
1094 for (line++; *line == ' ' || *line == '\t'; line++) {
1095 continue;
1096 }
1097
1098 /*
1099 * Find what type of if we're dealing with. The result is left
1100 * in ifp and isElse is set TRUE if it's an elif line.
1101 */
1102 if (line[0] == 'e' && line[1] == 'l') {
1103 line += 2;
1104 isElse = TRUE;
1105 } else if (strncmp (line, "endif", 5) == 0) {
1106 /*
1107 * End of a conditional section. If skipIfLevel is non-zero, that
1108 * conditional was skipped, so lines following it should also be
1109 * skipped. Hence, we return COND_SKIP. Otherwise, the conditional
1110 * was read so succeeding lines should be parsed (think about it...)
1111 * so we return COND_PARSE, unless this endif isn't paired with
1112 * a decent if.
1113 */
1114 if (skipIfLevel != 0) {
1115 skipIfLevel -= 1;
1116 return (COND_SKIP);
1117 } else {
1118 if (condTop == MAXIF) {
1119 Parse_Error (level, "if-less endif");
1120 return (COND_INVALID);
1121 } else {
1122 skipLine = FALSE;
1123 condTop += 1;
1124 return (COND_PARSE);
1125 }
1126 }
1127 } else {
1128 isElse = FALSE;
1129 }
1130
1131 /*
1132 * Figure out what sort of conditional it is -- what its default
1133 * function is, etc. -- by looking in the table of valid "ifs"
1134 */
1135 for (ifp = ifs; ifp->form != (char *)0; ifp++) {
1136 if (strncmp (ifp->form, line, ifp->formlen) == 0) {
1137 break;
1138 }
1139 }
1140
1141 if (ifp->form == (char *) 0) {
1142 /*
1143 * Nothing fit. If the first word on the line is actually
1144 * "else", it's a valid conditional whose value is the inverse
1145 * of the previous if we parsed.
1146 */
1147 if (isElse && (line[0] == 's') && (line[1] == 'e')) {
1148 if (condTop == MAXIF) {
1149 Parse_Error (level, "if-less else");
1150 return (COND_INVALID);
1151 } else if (skipIfLevel == 0) {
1152 value = !condStack[condTop];
1153 } else {
1154 return (COND_SKIP);
1155 }
1156 } else {
1157 /*
1158 * Not a valid conditional type. No error...
1159 */
1160 return (COND_INVALID);
1161 }
1162 } else {
1163 if (isElse) {
1164 if (condTop == MAXIF) {
1165 Parse_Error (level, "if-less elif");
1166 return (COND_INVALID);
1167 } else if (skipIfLevel != 0) {
1168 /*
1169 * If skipping this conditional, just ignore the whole thing.
1170 * If we don't, the user might be employing a variable that's
1171 * undefined, for which there's an enclosing ifdef that
1172 * we're skipping...
1173 */
1174 return(COND_SKIP);
1175 }
1176 } else if (skipLine) {
1177 /*
1178 * Don't even try to evaluate a conditional that's not an else if
1179 * we're skipping things...
1180 */
1181 skipIfLevel += 1;
1182 return(COND_SKIP);
1183 }
1184
1185 /*
1186 * Initialize file-global variables for parsing
1187 */
1188 condDefProc = ifp->defProc;
1189 condInvert = ifp->doNot;
1190
1191 line += ifp->formlen;
1192
1193 while (*line == ' ' || *line == '\t') {
1194 line++;
1195 }
1196
1197 condExpr = line;
1198 condPushBack = None;
1199
1200 switch (CondE(TRUE)) {
1201 case True:
1202 if (CondToken(TRUE) == EndOfFile) {
1203 value = TRUE;
1204 break;
1205 }
1206 goto err;
1207 /*FALLTHRU*/
1208 case False:
1209 if (CondToken(TRUE) == EndOfFile) {
1210 value = FALSE;
1211 break;
1212 }
1213 /*FALLTHRU*/
1214 case Err:
1215 err:
1216 Parse_Error (level, "Malformed conditional (%s)",
1217 line);
1218 return (COND_INVALID);
1219 default:
1220 break;
1221 }
1222 }
1223 if (!isElse) {
1224 condTop -= 1;
1225 } else if ((skipIfLevel != 0) || condStack[condTop]) {
1226 /*
1227 * If this is an else-type conditional, it should only take effect
1228 * if its corresponding if was evaluated and FALSE. If its if was
1229 * TRUE or skipped, we return COND_SKIP (and start skipping in case
1230 * we weren't already), leaving the stack unmolested so later elif's
1231 * don't screw up...
1232 */
1233 skipLine = TRUE;
1234 return (COND_SKIP);
1235 }
1236
1237 if (condTop < 0) {
1238 /*
1239 * This is the one case where we can definitely proclaim a fatal
1240 * error. If we don't, we're hosed.
1241 */
1242 Parse_Error (PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
1243 return (COND_INVALID);
1244 } else {
1245 condStack[condTop] = value;
1246 skipLine = !value;
1247 return (value ? COND_PARSE : COND_SKIP);
1248 }
1249 }
1250
1251 /*-
1253 *-----------------------------------------------------------------------
1254 * Cond_End --
1255 * Make sure everything's clean at the end of a makefile.
1256 *
1257 * Results:
1258 * None.
1259 *
1260 * Side Effects:
1261 * Parse_Error will be called if open conditionals are around.
1262 *
1263 *-----------------------------------------------------------------------
1264 */
1265 void
1266 Cond_End()
1267 {
1268 if (condTop != MAXIF) {
1269 Parse_Error(PARSE_FATAL, "%d open conditional%s", MAXIF-condTop,
1270 MAXIF-condTop == 1 ? "" : "s");
1271 }
1272 condTop = MAXIF;
1273 }
1274