cond.c revision 1.30 1 /* $NetBSD: cond.c,v 1.30 2006/03/31 21:58:08 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.30 2006/03/31 21:58:08 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.30 2006/03/31 21:58:08 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 void *ap = strdup(arg);
1002 if (arg)
1003 free(arg);
1004 t = (!doEval || (* evalProc) (arglen, ap) ?
1005 (invert ? False : True) :
1006 (invert ? True : False));
1007 break;
1008 }
1009 }
1010 } else {
1011 t = condPushBack;
1012 condPushBack = None;
1013 }
1014 return (t);
1015 }
1016
1017 /*-
1019 *-----------------------------------------------------------------------
1020 * CondT --
1021 * Parse a single term in the expression. This consists of a terminal
1022 * symbol or Not and a terminal symbol (not including the binary
1023 * operators):
1024 * T -> defined(variable) | make(target) | exists(file) | symbol
1025 * T -> ! T | ( E )
1026 *
1027 * Results:
1028 * True, False or Err.
1029 *
1030 * Side Effects:
1031 * Tokens are consumed.
1032 *
1033 *-----------------------------------------------------------------------
1034 */
1035 static Token
1036 CondT(Boolean doEval)
1037 {
1038 Token t;
1039
1040 t = CondToken(doEval);
1041
1042 if (t == EndOfFile) {
1043 /*
1044 * If we reached the end of the expression, the expression
1045 * is malformed...
1046 */
1047 t = Err;
1048 } else if (t == LParen) {
1049 /*
1050 * T -> ( E )
1051 */
1052 t = CondE(doEval);
1053 if (t != Err) {
1054 if (CondToken(doEval) != RParen) {
1055 t = Err;
1056 }
1057 }
1058 } else if (t == Not) {
1059 t = CondT(doEval);
1060 if (t == True) {
1061 t = False;
1062 } else if (t == False) {
1063 t = True;
1064 }
1065 }
1066 return (t);
1067 }
1068
1069 /*-
1071 *-----------------------------------------------------------------------
1072 * CondF --
1073 * Parse a conjunctive factor (nice name, wot?)
1074 * F -> T && F | T
1075 *
1076 * Results:
1077 * True, False or Err
1078 *
1079 * Side Effects:
1080 * Tokens are consumed.
1081 *
1082 *-----------------------------------------------------------------------
1083 */
1084 static Token
1085 CondF(Boolean doEval)
1086 {
1087 Token l, o;
1088
1089 l = CondT(doEval);
1090 if (l != Err) {
1091 o = CondToken(doEval);
1092
1093 if (o == And) {
1094 /*
1095 * F -> T && F
1096 *
1097 * If T is False, the whole thing will be False, but we have to
1098 * parse the r.h.s. anyway (to throw it away).
1099 * If T is True, the result is the r.h.s., be it an Err or no.
1100 */
1101 if (l == True) {
1102 l = CondF(doEval);
1103 } else {
1104 (void)CondF(FALSE);
1105 }
1106 } else {
1107 /*
1108 * F -> T
1109 */
1110 CondPushBack(o);
1111 }
1112 }
1113 return (l);
1114 }
1115
1116 /*-
1118 *-----------------------------------------------------------------------
1119 * CondE --
1120 * Main expression production.
1121 * E -> F || E | F
1122 *
1123 * Results:
1124 * True, False or Err.
1125 *
1126 * Side Effects:
1127 * Tokens are, of course, consumed.
1128 *
1129 *-----------------------------------------------------------------------
1130 */
1131 static Token
1132 CondE(Boolean doEval)
1133 {
1134 Token l, o;
1135
1136 l = CondF(doEval);
1137 if (l != Err) {
1138 o = CondToken(doEval);
1139
1140 if (o == Or) {
1141 /*
1142 * E -> F || E
1143 *
1144 * A similar thing occurs for ||, except that here we make sure
1145 * the l.h.s. is False before we bother to evaluate the r.h.s.
1146 * Once again, if l is False, the result is the r.h.s. and once
1147 * again if l is True, we parse the r.h.s. to throw it away.
1148 */
1149 if (l == False) {
1150 l = CondE(doEval);
1151 } else {
1152 (void)CondE(FALSE);
1153 }
1154 } else {
1155 /*
1156 * E -> F
1157 */
1158 CondPushBack(o);
1159 }
1160 }
1161 return (l);
1162 }
1163
1164 /*-
1165 *-----------------------------------------------------------------------
1166 * Cond_EvalExpression --
1167 * Evaluate an expression in the passed line. The expression
1168 * consists of &&, ||, !, make(target), defined(variable)
1169 * and parenthetical groupings thereof.
1170 *
1171 * Results:
1172 * COND_PARSE if the condition was valid grammatically
1173 * COND_INVALID if not a valid conditional.
1174 *
1175 * (*value) is set to the boolean value of the condition
1176 *
1177 * Side Effects:
1178 * None.
1179 *
1180 *-----------------------------------------------------------------------
1181 */
1182 int
1183 Cond_EvalExpression(int dosetup, char *line, Boolean *value, int eprint)
1184 {
1185 if (dosetup) {
1186 condDefProc = CondDoDefined;
1187 condInvert = 0;
1188 }
1189
1190 while (*line == ' ' || *line == '\t')
1191 line++;
1192
1193 condExpr = line;
1194 condPushBack = None;
1195
1196 switch (CondE(TRUE)) {
1197 case True:
1198 if (CondToken(TRUE) == EndOfFile) {
1199 *value = TRUE;
1200 break;
1201 }
1202 goto err;
1203 /*FALLTHRU*/
1204 case False:
1205 if (CondToken(TRUE) == EndOfFile) {
1206 *value = FALSE;
1207 break;
1208 }
1209 /*FALLTHRU*/
1210 case Err:
1211 err:
1212 if (eprint)
1213 Parse_Error(PARSE_FATAL, "Malformed conditional (%s)",
1214 line);
1215 return (COND_INVALID);
1216 default:
1217 break;
1218 }
1219
1220 return COND_PARSE;
1221 }
1222
1223
1224 /*-
1226 *-----------------------------------------------------------------------
1227 * Cond_Eval --
1228 * Evaluate the conditional in the passed line. The line
1229 * looks like this:
1230 * #<cond-type> <expr>
1231 * where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1232 * ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1233 * and <expr> consists of &&, ||, !, make(target), defined(variable)
1234 * and parenthetical groupings thereof.
1235 *
1236 * Input:
1237 * line Line to parse
1238 *
1239 * Results:
1240 * COND_PARSE if should parse lines after the conditional
1241 * COND_SKIP if should skip lines after the conditional
1242 * COND_INVALID if not a valid conditional.
1243 *
1244 * Side Effects:
1245 * None.
1246 *
1247 *-----------------------------------------------------------------------
1248 */
1249 int
1250 Cond_Eval(char *line)
1251 {
1252 struct If *ifp;
1253 Boolean isElse;
1254 Boolean value = FALSE;
1255 int level; /* Level at which to report errors. */
1256
1257 level = PARSE_FATAL;
1258
1259 for (line++; *line == ' ' || *line == '\t'; line++) {
1260 continue;
1261 }
1262
1263 /*
1264 * Find what type of if we're dealing with. The result is left
1265 * in ifp and isElse is set TRUE if it's an elif line.
1266 */
1267 if (line[0] == 'e' && line[1] == 'l') {
1268 line += 2;
1269 isElse = TRUE;
1270 } else if (istoken(line, "endif", 5)) {
1271 /*
1272 * End of a conditional section. If skipIfLevel is non-zero, that
1273 * conditional was skipped, so lines following it should also be
1274 * skipped. Hence, we return COND_SKIP. Otherwise, the conditional
1275 * was read so succeeding lines should be parsed (think about it...)
1276 * so we return COND_PARSE, unless this endif isn't paired with
1277 * a decent if.
1278 */
1279 finalElse[condTop][skipIfLevel] = FALSE;
1280 if (skipIfLevel != 0) {
1281 skipIfLevel -= 1;
1282 return (COND_SKIP);
1283 } else {
1284 if (condTop == MAXIF) {
1285 Parse_Error(level, "if-less endif");
1286 return (COND_INVALID);
1287 } else {
1288 skipLine = FALSE;
1289 condTop += 1;
1290 return (COND_PARSE);
1291 }
1292 }
1293 } else {
1294 isElse = FALSE;
1295 }
1296
1297 /*
1298 * Figure out what sort of conditional it is -- what its default
1299 * function is, etc. -- by looking in the table of valid "ifs"
1300 */
1301 for (ifp = ifs; ifp->form != NULL; ifp++) {
1302 if (istoken(ifp->form, line, ifp->formlen)) {
1303 break;
1304 }
1305 }
1306
1307 if (ifp->form == NULL) {
1308 /*
1309 * Nothing fit. If the first word on the line is actually
1310 * "else", it's a valid conditional whose value is the inverse
1311 * of the previous if we parsed.
1312 */
1313 if (isElse && istoken(line, "se", 2)) {
1314 if (finalElse[condTop][skipIfLevel]) {
1315 Parse_Error(PARSE_WARNING, "extra else");
1316 } else {
1317 finalElse[condTop][skipIfLevel] = TRUE;
1318 }
1319 if (condTop == MAXIF) {
1320 Parse_Error(level, "if-less else");
1321 return (COND_INVALID);
1322 } else if (skipIfLevel == 0) {
1323 value = !condStack[condTop];
1324 } else {
1325 return (COND_SKIP);
1326 }
1327 } else {
1328 /*
1329 * Not a valid conditional type. No error...
1330 */
1331 return (COND_INVALID);
1332 }
1333 } else {
1334 if (isElse) {
1335 if (condTop == MAXIF) {
1336 Parse_Error(level, "if-less elif");
1337 return (COND_INVALID);
1338 } else if (skipIfLevel != 0) {
1339 /*
1340 * If skipping this conditional, just ignore the whole thing.
1341 * If we don't, the user might be employing a variable that's
1342 * undefined, for which there's an enclosing ifdef that
1343 * we're skipping...
1344 */
1345 return(COND_SKIP);
1346 }
1347 } else if (skipLine) {
1348 /*
1349 * Don't even try to evaluate a conditional that's not an else if
1350 * we're skipping things...
1351 */
1352 skipIfLevel += 1;
1353 if (skipIfLevel >= MAXIF) {
1354 Parse_Error(PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
1355 return (COND_INVALID);
1356 }
1357 finalElse[condTop][skipIfLevel] = FALSE;
1358 return(COND_SKIP);
1359 }
1360
1361 /*
1362 * Initialize file-global variables for parsing
1363 */
1364 condDefProc = ifp->defProc;
1365 condInvert = ifp->doNot;
1366
1367 line += ifp->formlen;
1368 if (Cond_EvalExpression(0, line, &value, 1) == COND_INVALID)
1369 return COND_INVALID;
1370 }
1371 if (!isElse) {
1372 condTop -= 1;
1373 finalElse[condTop][skipIfLevel] = FALSE;
1374 } else if ((skipIfLevel != 0) || condStack[condTop]) {
1375 /*
1376 * If this is an else-type conditional, it should only take effect
1377 * if its corresponding if was evaluated and FALSE. If its if was
1378 * TRUE or skipped, we return COND_SKIP (and start skipping in case
1379 * we weren't already), leaving the stack unmolested so later elif's
1380 * don't screw up...
1381 */
1382 skipLine = TRUE;
1383 return (COND_SKIP);
1384 }
1385
1386 if (condTop < 0) {
1387 /*
1388 * This is the one case where we can definitely proclaim a fatal
1389 * error. If we don't, we're hosed.
1390 */
1391 Parse_Error(PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
1392 return (COND_INVALID);
1393 } else {
1394 condStack[condTop] = value;
1395 skipLine = !value;
1396 return (value ? COND_PARSE : COND_SKIP);
1397 }
1398 }
1399
1400
1401
1402 /*-
1404 *-----------------------------------------------------------------------
1405 * Cond_End --
1406 * Make sure everything's clean at the end of a makefile.
1407 *
1408 * Results:
1409 * None.
1410 *
1411 * Side Effects:
1412 * Parse_Error will be called if open conditionals are around.
1413 *
1414 *-----------------------------------------------------------------------
1415 */
1416 void
1417 Cond_End(void)
1418 {
1419 if (condTop != MAXIF) {
1420 Parse_Error(PARSE_FATAL, "%d open conditional%s", MAXIF-condTop,
1421 MAXIF-condTop == 1 ? "" : "s");
1422 }
1423 condTop = MAXIF;
1424 }
1425