cond.c revision 1.34 1 /* $NetBSD: cond.c,v 1.34 2006/10/15 08:38:21 dsl 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.34 2006/10/15 08:38:21 dsl 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.34 2006/10/15 08:38:21 dsl 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 if (DEBUG(COND)) {
429 fprintf(debug_file, "exists(%s) result is \"%s\"\n",
430 arg, path ? path : "");
431 }
432 return (result);
433 }
434
435 /*-
437 *-----------------------------------------------------------------------
438 * CondDoTarget --
439 * See if the given node exists and is an actual target.
440 *
441 * Results:
442 * TRUE if the node exists as a target and FALSE if it does not.
443 *
444 * Side Effects:
445 * None.
446 *
447 *-----------------------------------------------------------------------
448 */
449 static Boolean
450 CondDoTarget(int argLen, char *arg)
451 {
452 char savec = arg[argLen];
453 Boolean result;
454 GNode *gn;
455
456 arg[argLen] = '\0';
457 gn = Targ_FindNode(arg, TARG_NOCREATE);
458 if ((gn != NILGNODE) && !OP_NOP(gn->type)) {
459 result = TRUE;
460 } else {
461 result = FALSE;
462 }
463 arg[argLen] = savec;
464 return (result);
465 }
466
467 /*-
468 *-----------------------------------------------------------------------
469 * CondDoCommands --
470 * See if the given node exists and is an actual target with commands
471 * associated with it.
472 *
473 * Results:
474 * TRUE if the node exists as a target and has commands associated with
475 * it and FALSE if it does not.
476 *
477 * Side Effects:
478 * None.
479 *
480 *-----------------------------------------------------------------------
481 */
482 static Boolean
483 CondDoCommands(int argLen, char *arg)
484 {
485 char savec = arg[argLen];
486 Boolean result;
487 GNode *gn;
488
489 arg[argLen] = '\0';
490 gn = Targ_FindNode(arg, TARG_NOCREATE);
491 if ((gn != NILGNODE) && !OP_NOP(gn->type) && !Lst_IsEmpty(gn->commands)) {
492 result = TRUE;
493 } else {
494 result = FALSE;
495 }
496 arg[argLen] = savec;
497 return (result);
498 }
499
500 /*-
502 *-----------------------------------------------------------------------
503 * CondCvtArg --
504 * Convert the given number into a double. If the number begins
505 * with 0x, it is interpreted as a hexadecimal integer
506 * and converted to a double from there. All other strings just have
507 * strtod called on them.
508 *
509 * Results:
510 * Sets 'value' to double value of string.
511 * Returns NULL if string was fully consumed,
512 * else returns remaining input.
513 *
514 * Side Effects:
515 * Can change 'value' even if string is not a valid number.
516 *
517 *
518 *-----------------------------------------------------------------------
519 */
520 static char *
521 CondCvtArg(char *str, double *value)
522 {
523 if ((*str == '0') && (str[1] == 'x')) {
524 long i;
525
526 for (str += 2, i = 0; *str; str++) {
527 int x;
528 if (isdigit((unsigned char) *str))
529 x = *str - '0';
530 else if (isxdigit((unsigned char) *str))
531 x = 10 + *str - isupper((unsigned char) *str) ? 'A' : 'a';
532 else
533 break;
534 i = (i << 4) + x;
535 }
536 *value = (double) i;
537 return *str ? str : NULL;
538 } else {
539 char *eptr;
540 *value = strtod(str, &eptr);
541 return *eptr ? eptr : NULL;
542 }
543 }
544
545 /*-
547 *-----------------------------------------------------------------------
548 * CondGetString --
549 * Get a string from a variable reference or an optionally quoted
550 * string. This is called for the lhs and rhs of string compares.
551 *
552 * Results:
553 * Sets freeIt if needed,
554 * Sets quoted if string was quoted,
555 * Returns NULL on error,
556 * else returns string - absent any quotes.
557 *
558 * Side Effects:
559 * Moves condExpr to end of this token.
560 *
561 *
562 *-----------------------------------------------------------------------
563 */
564 /* coverity:[+alloc : arg-*2] */
565 static char *
566 CondGetString(Boolean doEval, Boolean *quoted, void **freeIt)
567 {
568 Buffer buf;
569 char *cp;
570 char *str;
571 int len;
572 int qt;
573 char *start;
574
575 buf = Buf_Init(0);
576 str = NULL;
577 *freeIt = NULL;
578 *quoted = qt = *condExpr == '"' ? 1 : 0;
579 if (qt)
580 condExpr++;
581 for (start = condExpr; *condExpr && str == NULL; condExpr++) {
582 switch (*condExpr) {
583 case '\\':
584 if (condExpr[1] != '\0') {
585 condExpr++;
586 Buf_AddByte(buf, (Byte)*condExpr);
587 }
588 break;
589 case '"':
590 if (qt) {
591 condExpr++; /* we don't want the quotes */
592 goto got_str;
593 } else
594 Buf_AddByte(buf, (Byte)*condExpr); /* likely? */
595 break;
596 case ')':
597 case '!':
598 case '=':
599 case '>':
600 case '<':
601 case ' ':
602 case '\t':
603 if (!qt)
604 goto got_str;
605 else
606 Buf_AddByte(buf, (Byte)*condExpr);
607 break;
608 case '$':
609 /* if we are in quotes, then an undefined variable is ok */
610 str = Var_Parse(condExpr, VAR_CMD, (qt ? 0 : doEval),
611 &len, freeIt);
612 if (str == var_Error) {
613 if (*freeIt) {
614 free(*freeIt);
615 *freeIt = NULL;
616 }
617 /*
618 * Even if !doEval, we still report syntax errors, which
619 * is what getting var_Error back with !doEval means.
620 */
621 str = NULL;
622 goto cleanup;
623 }
624 condExpr += len;
625 /*
626 * If the '$' was first char (no quotes), and we are
627 * followed by space, the operator or end of expression,
628 * we are done.
629 */
630 if ((condExpr == start + len) &&
631 (*condExpr == '\0' ||
632 isspace((unsigned char) *condExpr) ||
633 strchr("!=><)", *condExpr))) {
634 goto cleanup;
635 }
636 /*
637 * Nope, we better copy str to buf
638 */
639 for (cp = str; *cp; cp++) {
640 Buf_AddByte(buf, (Byte)*cp);
641 }
642 if (*freeIt) {
643 free(*freeIt);
644 *freeIt = NULL;
645 }
646 str = NULL; /* not finished yet */
647 condExpr--; /* don't skip over next char */
648 break;
649 default:
650 Buf_AddByte(buf, (Byte)*condExpr);
651 break;
652 }
653 }
654 got_str:
655 Buf_AddByte(buf, (Byte)'\0');
656 str = (char *)Buf_GetAll(buf, NULL);
657 *freeIt = str;
658 cleanup:
659 Buf_Destroy(buf, FALSE);
660 return str;
661 }
662
663 /*-
665 *-----------------------------------------------------------------------
666 * CondToken --
667 * Return the next token from the input.
668 *
669 * Results:
670 * A Token for the next lexical token in the stream.
671 *
672 * Side Effects:
673 * condPushback will be set back to None if it is used.
674 *
675 *-----------------------------------------------------------------------
676 */
677 static Token
678 CondToken(Boolean doEval)
679 {
680 Token t;
681
682 if (condPushBack == None) {
683 while (*condExpr == ' ' || *condExpr == '\t') {
684 condExpr++;
685 }
686 switch (*condExpr) {
687 case '(':
688 t = LParen;
689 condExpr++;
690 break;
691 case ')':
692 t = RParen;
693 condExpr++;
694 break;
695 case '|':
696 if (condExpr[1] == '|') {
697 condExpr++;
698 }
699 condExpr++;
700 t = Or;
701 break;
702 case '&':
703 if (condExpr[1] == '&') {
704 condExpr++;
705 }
706 condExpr++;
707 t = And;
708 break;
709 case '!':
710 t = Not;
711 condExpr++;
712 break;
713 case '#':
714 case '\n':
715 case '\0':
716 t = EndOfFile;
717 break;
718 case '"':
719 case '$': {
720 char *lhs;
721 char *rhs;
722 char *op;
723 void *lhsFree;
724 void *rhsFree;
725 Boolean lhsQuoted;
726 Boolean rhsQuoted;
727
728 rhs = NULL;
729 lhsFree = rhsFree = FALSE;
730 lhsQuoted = rhsQuoted = FALSE;
731
732 /*
733 * Parse the variable spec and skip over it, saving its
734 * value in lhs.
735 */
736 t = Err;
737 lhs = CondGetString(doEval, &lhsQuoted, &lhsFree);
738 if (!lhs) {
739 if (lhsFree)
740 free(lhsFree);
741 return Err;
742 }
743 /*
744 * Skip whitespace to get to the operator
745 */
746 while (isspace((unsigned char) *condExpr))
747 condExpr++;
748
749 /*
750 * Make sure the operator is a valid one. If it isn't a
751 * known relational operator, pretend we got a
752 * != 0 comparison.
753 */
754 op = condExpr;
755 switch (*condExpr) {
756 case '!':
757 case '=':
758 case '<':
759 case '>':
760 if (condExpr[1] == '=') {
761 condExpr += 2;
762 } else {
763 condExpr += 1;
764 }
765 break;
766 default:
767 op = UNCONST("!=");
768 if (lhsQuoted)
769 rhs = UNCONST("");
770 else
771 rhs = UNCONST("0");
772
773 goto do_compare;
774 }
775 while (isspace((unsigned char) *condExpr)) {
776 condExpr++;
777 }
778 if (*condExpr == '\0') {
779 Parse_Error(PARSE_WARNING,
780 "Missing right-hand-side of operator");
781 goto error;
782 }
783 rhs = CondGetString(doEval, &rhsQuoted, &rhsFree);
784 if (!rhs) {
785 if (lhsFree)
786 free(lhsFree);
787 if (rhsFree)
788 free(rhsFree);
789 return Err;
790 }
791 do_compare:
792 if (rhsQuoted || lhsQuoted) {
793 do_string_compare:
794 if (((*op != '!') && (*op != '=')) || (op[1] != '=')) {
795 Parse_Error(PARSE_WARNING,
796 "String comparison operator should be either == or !=");
797 goto error;
798 }
799
800 if (DEBUG(COND)) {
801 fprintf(debug_file, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
802 lhs, rhs, op);
803 }
804 /*
805 * Null-terminate rhs and perform the comparison.
806 * t is set to the result.
807 */
808 if (*op == '=') {
809 t = strcmp(lhs, rhs) ? False : True;
810 } else {
811 t = strcmp(lhs, rhs) ? True : False;
812 }
813 } else {
814 /*
815 * rhs is either a float or an integer. Convert both the
816 * lhs and the rhs to a double and compare the two.
817 */
818 double left, right;
819 char *cp;
820
821 if (CondCvtArg(lhs, &left))
822 goto do_string_compare;
823 if ((cp = CondCvtArg(rhs, &right)) &&
824 cp == rhs)
825 goto do_string_compare;
826
827 if (DEBUG(COND)) {
828 fprintf(debug_file, "left = %f, right = %f, op = %.2s\n", left,
829 right, op);
830 }
831 switch(op[0]) {
832 case '!':
833 if (op[1] != '=') {
834 Parse_Error(PARSE_WARNING,
835 "Unknown operator");
836 goto error;
837 }
838 t = (left != right ? True : False);
839 break;
840 case '=':
841 if (op[1] != '=') {
842 Parse_Error(PARSE_WARNING,
843 "Unknown operator");
844 goto error;
845 }
846 t = (left == right ? True : False);
847 break;
848 case '<':
849 if (op[1] == '=') {
850 t = (left <= right ? True : False);
851 } else {
852 t = (left < right ? True : False);
853 }
854 break;
855 case '>':
856 if (op[1] == '=') {
857 t = (left >= right ? True : False);
858 } else {
859 t = (left > right ? True : False);
860 }
861 break;
862 }
863 }
864 error:
865 if (lhsFree)
866 free(lhsFree);
867 if (rhsFree)
868 free(rhsFree);
869 break;
870 }
871 default: {
872 Boolean (*evalProc)(int, char *);
873 Boolean invert = FALSE;
874 char *arg = NULL;
875 int arglen = 0;
876
877 if (istoken(condExpr, "defined", 7)) {
878 /*
879 * Use CondDoDefined to evaluate the argument and
880 * CondGetArg to extract the argument from the 'function
881 * call'.
882 */
883 evalProc = CondDoDefined;
884 condExpr += 7;
885 arglen = CondGetArg(&condExpr, &arg, "defined", TRUE);
886 if (arglen == 0) {
887 condExpr -= 7;
888 goto use_default;
889 }
890 } else if (istoken(condExpr, "make", 4)) {
891 /*
892 * Use CondDoMake to evaluate the argument and
893 * CondGetArg to extract the argument from the 'function
894 * call'.
895 */
896 evalProc = CondDoMake;
897 condExpr += 4;
898 arglen = CondGetArg(&condExpr, &arg, "make", TRUE);
899 if (arglen == 0) {
900 condExpr -= 4;
901 goto use_default;
902 }
903 } else if (istoken(condExpr, "exists", 6)) {
904 /*
905 * Use CondDoExists to evaluate the argument and
906 * CondGetArg to extract the argument from the
907 * 'function call'.
908 */
909 evalProc = CondDoExists;
910 condExpr += 6;
911 arglen = CondGetArg(&condExpr, &arg, "exists", TRUE);
912 if (arglen == 0) {
913 condExpr -= 6;
914 goto use_default;
915 }
916 } else if (istoken(condExpr, "empty", 5)) {
917 /*
918 * Use Var_Parse to parse the spec in parens and return
919 * True if the resulting string is empty.
920 */
921 int length;
922 void *freeIt;
923 char *val;
924
925 condExpr += 5;
926
927 for (arglen = 0;
928 condExpr[arglen] != '(' && condExpr[arglen] != '\0';
929 arglen += 1)
930 continue;
931
932 if (condExpr[arglen] != '\0') {
933 val = Var_Parse(&condExpr[arglen - 1], VAR_CMD,
934 FALSE, &length, &freeIt);
935 if (val == var_Error) {
936 t = Err;
937 } else {
938 /*
939 * A variable is empty when it just contains
940 * spaces... 4/15/92, christos
941 */
942 char *p;
943 for (p = val; *p && isspace((unsigned char)*p); p++)
944 continue;
945 t = (*p == '\0') ? True : False;
946 }
947 if (freeIt) {
948 free(freeIt);
949 }
950 /*
951 * Advance condExpr to beyond the closing ). Note that
952 * we subtract one from arglen + length b/c length
953 * is calculated from condExpr[arglen - 1].
954 */
955 condExpr += arglen + length - 1;
956 } else {
957 condExpr -= 5;
958 goto use_default;
959 }
960 break;
961 } else if (istoken(condExpr, "target", 6)) {
962 /*
963 * Use CondDoTarget to evaluate the argument and
964 * CondGetArg to extract the argument from the
965 * 'function call'.
966 */
967 evalProc = CondDoTarget;
968 condExpr += 6;
969 arglen = CondGetArg(&condExpr, &arg, "target", TRUE);
970 if (arglen == 0) {
971 condExpr -= 6;
972 goto use_default;
973 }
974 } else if (istoken(condExpr, "commands", 8)) {
975 /*
976 * Use CondDoCommands to evaluate the argument and
977 * CondGetArg to extract the argument from the
978 * 'function call'.
979 */
980 evalProc = CondDoCommands;
981 condExpr += 8;
982 arglen = CondGetArg(&condExpr, &arg, "commands", TRUE);
983 if (arglen == 0) {
984 condExpr -= 8;
985 goto use_default;
986 }
987 } else {
988 /*
989 * The symbol is itself the argument to the default
990 * function. We advance condExpr to the end of the symbol
991 * by hand (the next whitespace, closing paren or
992 * binary operator) and set to invert the evaluation
993 * function if condInvert is TRUE.
994 */
995 use_default:
996 invert = condInvert;
997 evalProc = condDefProc;
998 arglen = CondGetArg(&condExpr, &arg, "", FALSE);
999 }
1000
1001 /*
1002 * Evaluate the argument using the set function. If invert
1003 * is TRUE, we invert the sense of the function.
1004 */
1005 t = (!doEval || (* evalProc) (arglen, arg) ?
1006 (invert ? False : True) :
1007 (invert ? True : False));
1008 if (arg)
1009 free(arg);
1010 break;
1011 }
1012 }
1013 } else {
1014 t = condPushBack;
1015 condPushBack = None;
1016 }
1017 return (t);
1018 }
1019
1020 /*-
1022 *-----------------------------------------------------------------------
1023 * CondT --
1024 * Parse a single term in the expression. This consists of a terminal
1025 * symbol or Not and a terminal symbol (not including the binary
1026 * operators):
1027 * T -> defined(variable) | make(target) | exists(file) | symbol
1028 * T -> ! T | ( E )
1029 *
1030 * Results:
1031 * True, False or Err.
1032 *
1033 * Side Effects:
1034 * Tokens are consumed.
1035 *
1036 *-----------------------------------------------------------------------
1037 */
1038 static Token
1039 CondT(Boolean doEval)
1040 {
1041 Token t;
1042
1043 t = CondToken(doEval);
1044
1045 if (t == EndOfFile) {
1046 /*
1047 * If we reached the end of the expression, the expression
1048 * is malformed...
1049 */
1050 t = Err;
1051 } else if (t == LParen) {
1052 /*
1053 * T -> ( E )
1054 */
1055 t = CondE(doEval);
1056 if (t != Err) {
1057 if (CondToken(doEval) != RParen) {
1058 t = Err;
1059 }
1060 }
1061 } else if (t == Not) {
1062 t = CondT(doEval);
1063 if (t == True) {
1064 t = False;
1065 } else if (t == False) {
1066 t = True;
1067 }
1068 }
1069 return (t);
1070 }
1071
1072 /*-
1074 *-----------------------------------------------------------------------
1075 * CondF --
1076 * Parse a conjunctive factor (nice name, wot?)
1077 * F -> T && F | T
1078 *
1079 * Results:
1080 * True, False or Err
1081 *
1082 * Side Effects:
1083 * Tokens are consumed.
1084 *
1085 *-----------------------------------------------------------------------
1086 */
1087 static Token
1088 CondF(Boolean doEval)
1089 {
1090 Token l, o;
1091
1092 l = CondT(doEval);
1093 if (l != Err) {
1094 o = CondToken(doEval);
1095
1096 if (o == And) {
1097 /*
1098 * F -> T && F
1099 *
1100 * If T is False, the whole thing will be False, but we have to
1101 * parse the r.h.s. anyway (to throw it away).
1102 * If T is True, the result is the r.h.s., be it an Err or no.
1103 */
1104 if (l == True) {
1105 l = CondF(doEval);
1106 } else {
1107 (void)CondF(FALSE);
1108 }
1109 } else {
1110 /*
1111 * F -> T
1112 */
1113 CondPushBack(o);
1114 }
1115 }
1116 return (l);
1117 }
1118
1119 /*-
1121 *-----------------------------------------------------------------------
1122 * CondE --
1123 * Main expression production.
1124 * E -> F || E | F
1125 *
1126 * Results:
1127 * True, False or Err.
1128 *
1129 * Side Effects:
1130 * Tokens are, of course, consumed.
1131 *
1132 *-----------------------------------------------------------------------
1133 */
1134 static Token
1135 CondE(Boolean doEval)
1136 {
1137 Token l, o;
1138
1139 l = CondF(doEval);
1140 if (l != Err) {
1141 o = CondToken(doEval);
1142
1143 if (o == Or) {
1144 /*
1145 * E -> F || E
1146 *
1147 * A similar thing occurs for ||, except that here we make sure
1148 * the l.h.s. is False before we bother to evaluate the r.h.s.
1149 * Once again, if l is False, the result is the r.h.s. and once
1150 * again if l is True, we parse the r.h.s. to throw it away.
1151 */
1152 if (l == False) {
1153 l = CondE(doEval);
1154 } else {
1155 (void)CondE(FALSE);
1156 }
1157 } else {
1158 /*
1159 * E -> F
1160 */
1161 CondPushBack(o);
1162 }
1163 }
1164 return (l);
1165 }
1166
1167 /*-
1168 *-----------------------------------------------------------------------
1169 * Cond_EvalExpression --
1170 * Evaluate an expression in the passed line. The expression
1171 * consists of &&, ||, !, make(target), defined(variable)
1172 * and parenthetical groupings thereof.
1173 *
1174 * Results:
1175 * COND_PARSE if the condition was valid grammatically
1176 * COND_INVALID if not a valid conditional.
1177 *
1178 * (*value) is set to the boolean value of the condition
1179 *
1180 * Side Effects:
1181 * None.
1182 *
1183 *-----------------------------------------------------------------------
1184 */
1185 int
1186 Cond_EvalExpression(int dosetup, char *line, Boolean *value, int eprint)
1187 {
1188 if (dosetup) {
1189 condDefProc = CondDoDefined;
1190 condInvert = 0;
1191 }
1192
1193 while (*line == ' ' || *line == '\t')
1194 line++;
1195
1196 condExpr = line;
1197 condPushBack = None;
1198
1199 switch (CondE(TRUE)) {
1200 case True:
1201 if (CondToken(TRUE) == EndOfFile) {
1202 *value = TRUE;
1203 break;
1204 }
1205 goto err;
1206 /*FALLTHRU*/
1207 case False:
1208 if (CondToken(TRUE) == EndOfFile) {
1209 *value = FALSE;
1210 break;
1211 }
1212 /*FALLTHRU*/
1213 case Err:
1214 err:
1215 if (eprint)
1216 Parse_Error(PARSE_FATAL, "Malformed conditional (%s)",
1217 line);
1218 return (COND_INVALID);
1219 default:
1220 break;
1221 }
1222
1223 return COND_PARSE;
1224 }
1225
1226
1227 /*-
1229 *-----------------------------------------------------------------------
1230 * Cond_Eval --
1231 * Evaluate the conditional in the passed line. The line
1232 * looks like this:
1233 * #<cond-type> <expr>
1234 * where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1235 * ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1236 * and <expr> consists of &&, ||, !, make(target), defined(variable)
1237 * and parenthetical groupings thereof.
1238 *
1239 * Input:
1240 * line Line to parse
1241 *
1242 * Results:
1243 * COND_PARSE if should parse lines after the conditional
1244 * COND_SKIP if should skip lines after the conditional
1245 * COND_INVALID if not a valid conditional.
1246 *
1247 * Side Effects:
1248 * None.
1249 *
1250 *-----------------------------------------------------------------------
1251 */
1252 int
1253 Cond_Eval(char *line)
1254 {
1255 struct If *ifp;
1256 Boolean isElse;
1257 Boolean value = FALSE;
1258 int level; /* Level at which to report errors. */
1259
1260 level = PARSE_FATAL;
1261
1262 for (line++; *line == ' ' || *line == '\t'; line++) {
1263 continue;
1264 }
1265
1266 /*
1267 * Find what type of if we're dealing with. The result is left
1268 * in ifp and isElse is set TRUE if it's an elif line.
1269 */
1270 if (line[0] == 'e' && line[1] == 'l') {
1271 line += 2;
1272 isElse = TRUE;
1273 } else if (istoken(line, "endif", 5)) {
1274 /*
1275 * End of a conditional section. If skipIfLevel is non-zero, that
1276 * conditional was skipped, so lines following it should also be
1277 * skipped. Hence, we return COND_SKIP. Otherwise, the conditional
1278 * was read so succeeding lines should be parsed (think about it...)
1279 * so we return COND_PARSE, unless this endif isn't paired with
1280 * a decent if.
1281 */
1282 finalElse[condTop][skipIfLevel] = FALSE;
1283 if (skipIfLevel != 0) {
1284 skipIfLevel -= 1;
1285 return (COND_SKIP);
1286 } else {
1287 if (condTop == MAXIF) {
1288 Parse_Error(level, "if-less endif");
1289 return (COND_INVALID);
1290 } else {
1291 skipLine = FALSE;
1292 condTop += 1;
1293 return (COND_PARSE);
1294 }
1295 }
1296 } else {
1297 isElse = FALSE;
1298 }
1299
1300 /*
1301 * Figure out what sort of conditional it is -- what its default
1302 * function is, etc. -- by looking in the table of valid "ifs"
1303 */
1304 for (ifp = ifs; ifp->form != NULL; ifp++) {
1305 if (istoken(ifp->form, line, ifp->formlen)) {
1306 break;
1307 }
1308 }
1309
1310 if (ifp->form == NULL) {
1311 /*
1312 * Nothing fit. If the first word on the line is actually
1313 * "else", it's a valid conditional whose value is the inverse
1314 * of the previous if we parsed.
1315 */
1316 if (isElse && istoken(line, "se", 2)) {
1317 if (finalElse[condTop][skipIfLevel]) {
1318 Parse_Error(PARSE_WARNING, "extra else");
1319 } else {
1320 finalElse[condTop][skipIfLevel] = TRUE;
1321 }
1322 if (condTop == MAXIF) {
1323 Parse_Error(level, "if-less else");
1324 return (COND_INVALID);
1325 } else if (skipIfLevel == 0) {
1326 value = !condStack[condTop];
1327 } else {
1328 return (COND_SKIP);
1329 }
1330 } else {
1331 /*
1332 * Not a valid conditional type. No error...
1333 */
1334 return (COND_INVALID);
1335 }
1336 } else {
1337 if (isElse) {
1338 if (condTop == MAXIF) {
1339 Parse_Error(level, "if-less elif");
1340 return (COND_INVALID);
1341 } else if (skipIfLevel != 0) {
1342 /*
1343 * If skipping this conditional, just ignore the whole thing.
1344 * If we don't, the user might be employing a variable that's
1345 * undefined, for which there's an enclosing ifdef that
1346 * we're skipping...
1347 */
1348 return(COND_SKIP);
1349 }
1350 } else if (skipLine) {
1351 /*
1352 * Don't even try to evaluate a conditional that's not an else if
1353 * we're skipping things...
1354 */
1355 skipIfLevel += 1;
1356 if (skipIfLevel >= MAXIF) {
1357 Parse_Error(PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
1358 return (COND_INVALID);
1359 }
1360 finalElse[condTop][skipIfLevel] = FALSE;
1361 return(COND_SKIP);
1362 }
1363
1364 /*
1365 * Initialize file-global variables for parsing
1366 */
1367 condDefProc = ifp->defProc;
1368 condInvert = ifp->doNot;
1369
1370 line += ifp->formlen;
1371 if (Cond_EvalExpression(0, line, &value, 1) == COND_INVALID)
1372 return COND_INVALID;
1373 }
1374 if (!isElse) {
1375 condTop -= 1;
1376 if (condTop < 0) {
1377 /*
1378 * This is the one case where we can definitely proclaim a fatal
1379 * error. If we don't, we're hosed.
1380 */
1381 Parse_Error(PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
1382 return (COND_INVALID);
1383 }
1384 finalElse[condTop][skipIfLevel] = FALSE;
1385 } else if ((skipIfLevel != 0) || condStack[condTop]) {
1386 /*
1387 * If this is an else-type conditional, it should only take effect
1388 * if its corresponding if was evaluated and FALSE. If its if was
1389 * TRUE or skipped, we return COND_SKIP (and start skipping in case
1390 * we weren't already), leaving the stack unmolested so later elif's
1391 * don't screw up...
1392 */
1393 skipLine = TRUE;
1394 return (COND_SKIP);
1395 }
1396
1397 condStack[condTop] = value;
1398 skipLine = !value;
1399 return (value ? COND_PARSE : COND_SKIP);
1400 }
1401
1402
1403
1404 /*-
1406 *-----------------------------------------------------------------------
1407 * Cond_End --
1408 * Make sure everything's clean at the end of a makefile.
1409 *
1410 * Results:
1411 * None.
1412 *
1413 * Side Effects:
1414 * Parse_Error will be called if open conditionals are around.
1415 *
1416 *-----------------------------------------------------------------------
1417 */
1418 void
1419 Cond_End(void)
1420 {
1421 if (condTop != MAXIF) {
1422 Parse_Error(PARSE_FATAL, "%d open conditional%s", MAXIF-condTop,
1423 MAXIF-condTop == 1 ? "" : "s");
1424 }
1425 condTop = MAXIF;
1426 }
1427