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