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