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