cond.c revision 1.37 1 /* $NetBSD: cond.c,v 1.37 2007/02/04 19:23:49 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.37 2007/02/04 19:23:49 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.37 2007/02/04 19:23:49 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 const 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 { "def", 3, FALSE, CondDoDefined },
162 { "ndef", 4, TRUE, CondDoDefined },
163 { "make", 4, FALSE, CondDoMake },
164 { "nmake", 5, TRUE, CondDoMake },
165 { "", 0, 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 static unsigned int cond_depth = 0; /* current .if nesting level */
176 static unsigned int cond_min_depth = 0; /* depth at makefile open */
177
178 static int
179 istoken(const char *str, const char *tok, size_t len)
180 {
181 return strncmp(str, tok, len) == 0 && !isalpha((unsigned char)str[len]);
182 }
183
184 /*-
185 *-----------------------------------------------------------------------
186 * CondPushBack --
187 * Push back the most recent token read. We only need one level of
188 * this, so the thing is just stored in 'condPushback'.
189 *
190 * Input:
191 * t Token to push back into the "stream"
192 *
193 * Results:
194 * None.
195 *
196 * Side Effects:
197 * condPushback is overwritten.
198 *
199 *-----------------------------------------------------------------------
200 */
201 static void
202 CondPushBack(Token t)
203 {
204 condPushBack = t;
205 }
206
207 /*-
209 *-----------------------------------------------------------------------
210 * CondGetArg --
211 * Find the argument of a built-in function.
212 *
213 * Input:
214 * parens TRUE if arg should be bounded by parens
215 *
216 * Results:
217 * The length of the argument and the address of the argument.
218 *
219 * Side Effects:
220 * The pointer is set to point to the closing parenthesis of the
221 * function call.
222 *
223 *-----------------------------------------------------------------------
224 */
225 static int
226 CondGetArg(char **linePtr, char **argPtr, const char *func, Boolean parens)
227 {
228 char *cp;
229 int argLen;
230 Buffer buf;
231
232 cp = *linePtr;
233 if (parens) {
234 while (*cp != '(' && *cp != '\0') {
235 cp++;
236 }
237 if (*cp == '(') {
238 cp++;
239 }
240 }
241
242 if (*cp == '\0') {
243 /*
244 * No arguments whatsoever. Because 'make' and 'defined' aren't really
245 * "reserved words", we don't print a message. I think this is better
246 * than hitting the user with a warning message every time s/he uses
247 * the word 'make' or 'defined' at the beginning of a symbol...
248 */
249 *argPtr = NULL;
250 return (0);
251 }
252
253 while (*cp == ' ' || *cp == '\t') {
254 cp++;
255 }
256
257 /*
258 * Create a buffer for the argument and start it out at 16 characters
259 * long. Why 16? Why not?
260 */
261 buf = Buf_Init(16);
262
263 while ((strchr(" \t)&|", *cp) == NULL) && (*cp != '\0')) {
264 if (*cp == '$') {
265 /*
266 * Parse the variable spec and install it as part of the argument
267 * if it's valid. We tell Var_Parse to complain on an undefined
268 * variable, so we don't do it too. Nor do we return an error,
269 * though perhaps we should...
270 */
271 char *cp2;
272 int len;
273 void *freeIt;
274
275 cp2 = Var_Parse(cp, VAR_CMD, TRUE, &len, &freeIt);
276 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
277 if (freeIt)
278 free(freeIt);
279 cp += len;
280 } else {
281 Buf_AddByte(buf, (Byte)*cp);
282 cp++;
283 }
284 }
285
286 Buf_AddByte(buf, (Byte)'\0');
287 *argPtr = (char *)Buf_GetAll(buf, &argLen);
288 Buf_Destroy(buf, FALSE);
289
290 while (*cp == ' ' || *cp == '\t') {
291 cp++;
292 }
293 if (parens && *cp != ')') {
294 Parse_Error(PARSE_WARNING, "Missing closing parenthesis for %s()",
295 func);
296 return (0);
297 } else if (parens) {
298 /*
299 * Advance pointer past close parenthesis.
300 */
301 cp++;
302 }
303
304 *linePtr = cp;
305 return (argLen);
306 }
307
308 /*-
310 *-----------------------------------------------------------------------
311 * CondDoDefined --
312 * Handle the 'defined' function for conditionals.
313 *
314 * Results:
315 * TRUE if the given variable is defined.
316 *
317 * Side Effects:
318 * None.
319 *
320 *-----------------------------------------------------------------------
321 */
322 static Boolean
323 CondDoDefined(int argLen, char *arg)
324 {
325 char savec = arg[argLen];
326 char *p1;
327 Boolean result;
328
329 arg[argLen] = '\0';
330 if (Var_Value(arg, VAR_CMD, &p1) != NULL) {
331 result = TRUE;
332 } else {
333 result = FALSE;
334 }
335 if (p1)
336 free(p1);
337 arg[argLen] = savec;
338 return (result);
339 }
340
341 /*-
343 *-----------------------------------------------------------------------
344 * CondStrMatch --
345 * Front-end for Str_Match so it returns 0 on match and non-zero
346 * on mismatch. Callback function for CondDoMake via Lst_Find
347 *
348 * Results:
349 * 0 if string matches pattern
350 *
351 * Side Effects:
352 * None
353 *
354 *-----------------------------------------------------------------------
355 */
356 static int
357 CondStrMatch(ClientData string, ClientData pattern)
358 {
359 return(!Str_Match((char *)string,(char *)pattern));
360 }
361
362 /*-
364 *-----------------------------------------------------------------------
365 * CondDoMake --
366 * Handle the 'make' function for conditionals.
367 *
368 * Results:
369 * TRUE if the given target is being made.
370 *
371 * Side Effects:
372 * None.
373 *
374 *-----------------------------------------------------------------------
375 */
376 static Boolean
377 CondDoMake(int argLen, char *arg)
378 {
379 char savec = arg[argLen];
380 Boolean result;
381
382 arg[argLen] = '\0';
383 if (Lst_Find(create, arg, CondStrMatch) == NILLNODE) {
384 result = FALSE;
385 } else {
386 result = TRUE;
387 }
388 arg[argLen] = savec;
389 return (result);
390 }
391
392 /*-
394 *-----------------------------------------------------------------------
395 * CondDoExists --
396 * See if the given file exists.
397 *
398 * Results:
399 * TRUE if the file exists and FALSE if it does not.
400 *
401 * Side Effects:
402 * None.
403 *
404 *-----------------------------------------------------------------------
405 */
406 static Boolean
407 CondDoExists(int argLen, char *arg)
408 {
409 char savec = arg[argLen];
410 Boolean result;
411 char *path;
412
413 arg[argLen] = '\0';
414 path = Dir_FindFile(arg, dirSearchPath);
415 if (path != NULL) {
416 result = TRUE;
417 free(path);
418 } else {
419 result = FALSE;
420 }
421 arg[argLen] = savec;
422 if (DEBUG(COND)) {
423 fprintf(debug_file, "exists(%s) result is \"%s\"\n",
424 arg, path ? path : "");
425 }
426 return (result);
427 }
428
429 /*-
431 *-----------------------------------------------------------------------
432 * CondDoTarget --
433 * See if the given node exists and is an actual target.
434 *
435 * Results:
436 * TRUE if the node exists as a target and FALSE if it does not.
437 *
438 * Side Effects:
439 * None.
440 *
441 *-----------------------------------------------------------------------
442 */
443 static Boolean
444 CondDoTarget(int argLen, char *arg)
445 {
446 char savec = arg[argLen];
447 Boolean result;
448 GNode *gn;
449
450 arg[argLen] = '\0';
451 gn = Targ_FindNode(arg, TARG_NOCREATE);
452 if ((gn != NILGNODE) && !OP_NOP(gn->type)) {
453 result = TRUE;
454 } else {
455 result = FALSE;
456 }
457 arg[argLen] = savec;
458 return (result);
459 }
460
461 /*-
462 *-----------------------------------------------------------------------
463 * CondDoCommands --
464 * See if the given node exists and is an actual target with commands
465 * associated with it.
466 *
467 * Results:
468 * TRUE if the node exists as a target and has commands associated with
469 * it and FALSE if it does not.
470 *
471 * Side Effects:
472 * None.
473 *
474 *-----------------------------------------------------------------------
475 */
476 static Boolean
477 CondDoCommands(int argLen, char *arg)
478 {
479 char savec = arg[argLen];
480 Boolean result;
481 GNode *gn;
482
483 arg[argLen] = '\0';
484 gn = Targ_FindNode(arg, TARG_NOCREATE);
485 if ((gn != NILGNODE) && !OP_NOP(gn->type) && !Lst_IsEmpty(gn->commands)) {
486 result = TRUE;
487 } else {
488 result = FALSE;
489 }
490 arg[argLen] = savec;
491 return (result);
492 }
493
494 /*-
496 *-----------------------------------------------------------------------
497 * CondCvtArg --
498 * Convert the given number into a double. If the number begins
499 * with 0x, it is interpreted as a hexadecimal integer
500 * and converted to a double from there. All other strings just have
501 * strtod called on them.
502 *
503 * Results:
504 * Sets 'value' to double value of string.
505 * Returns NULL if string was fully consumed,
506 * else returns remaining input.
507 *
508 * Side Effects:
509 * Can change 'value' even if string is not a valid number.
510 *
511 *
512 *-----------------------------------------------------------------------
513 */
514 static char *
515 CondCvtArg(char *str, double *value)
516 {
517 if ((*str == '0') && (str[1] == 'x')) {
518 long i;
519
520 for (str += 2, i = 0; *str; str++) {
521 int x;
522 if (isdigit((unsigned char) *str))
523 x = *str - '0';
524 else if (isxdigit((unsigned char) *str))
525 x = 10 + *str - isupper((unsigned char) *str) ? 'A' : 'a';
526 else
527 break;
528 i = (i << 4) + x;
529 }
530 *value = (double) i;
531 return *str ? str : NULL;
532 } else {
533 char *eptr;
534 *value = strtod(str, &eptr);
535 return *eptr ? eptr : NULL;
536 }
537 }
538
539 /*-
541 *-----------------------------------------------------------------------
542 * CondGetString --
543 * Get a string from a variable reference or an optionally quoted
544 * string. This is called for the lhs and rhs of string compares.
545 *
546 * Results:
547 * Sets freeIt if needed,
548 * Sets quoted if string was quoted,
549 * Returns NULL on error,
550 * else returns string - absent any quotes.
551 *
552 * Side Effects:
553 * Moves condExpr to end of this token.
554 *
555 *
556 *-----------------------------------------------------------------------
557 */
558 /* coverity:[+alloc : arg-*2] */
559 static char *
560 CondGetString(Boolean doEval, Boolean *quoted, void **freeIt)
561 {
562 Buffer buf;
563 char *cp;
564 char *str;
565 int len;
566 int qt;
567 char *start;
568
569 buf = Buf_Init(0);
570 str = NULL;
571 *freeIt = NULL;
572 *quoted = qt = *condExpr == '"' ? 1 : 0;
573 if (qt)
574 condExpr++;
575 for (start = condExpr; *condExpr && str == NULL; condExpr++) {
576 switch (*condExpr) {
577 case '\\':
578 if (condExpr[1] != '\0') {
579 condExpr++;
580 Buf_AddByte(buf, (Byte)*condExpr);
581 }
582 break;
583 case '"':
584 if (qt) {
585 condExpr++; /* we don't want the quotes */
586 goto got_str;
587 } else
588 Buf_AddByte(buf, (Byte)*condExpr); /* likely? */
589 break;
590 case ')':
591 case '!':
592 case '=':
593 case '>':
594 case '<':
595 case ' ':
596 case '\t':
597 if (!qt)
598 goto got_str;
599 else
600 Buf_AddByte(buf, (Byte)*condExpr);
601 break;
602 case '$':
603 /* if we are in quotes, then an undefined variable is ok */
604 str = Var_Parse(condExpr, VAR_CMD, (qt ? 0 : doEval),
605 &len, freeIt);
606 if (str == var_Error) {
607 if (*freeIt) {
608 free(*freeIt);
609 *freeIt = NULL;
610 }
611 /*
612 * Even if !doEval, we still report syntax errors, which
613 * is what getting var_Error back with !doEval means.
614 */
615 str = NULL;
616 goto cleanup;
617 }
618 condExpr += len;
619 /*
620 * If the '$' was first char (no quotes), and we are
621 * followed by space, the operator or end of expression,
622 * we are done.
623 */
624 if ((condExpr == start + len) &&
625 (*condExpr == '\0' ||
626 isspace((unsigned char) *condExpr) ||
627 strchr("!=><)", *condExpr))) {
628 goto cleanup;
629 }
630 /*
631 * Nope, we better copy str to buf
632 */
633 for (cp = str; *cp; cp++) {
634 Buf_AddByte(buf, (Byte)*cp);
635 }
636 if (*freeIt) {
637 free(*freeIt);
638 *freeIt = NULL;
639 }
640 str = NULL; /* not finished yet */
641 condExpr--; /* don't skip over next char */
642 break;
643 default:
644 Buf_AddByte(buf, (Byte)*condExpr);
645 break;
646 }
647 }
648 got_str:
649 Buf_AddByte(buf, (Byte)'\0');
650 str = (char *)Buf_GetAll(buf, NULL);
651 *freeIt = str;
652 cleanup:
653 Buf_Destroy(buf, FALSE);
654 return str;
655 }
656
657 /*-
659 *-----------------------------------------------------------------------
660 * CondToken --
661 * Return the next token from the input.
662 *
663 * Results:
664 * A Token for the next lexical token in the stream.
665 *
666 * Side Effects:
667 * condPushback will be set back to None if it is used.
668 *
669 *-----------------------------------------------------------------------
670 */
671 static Token
672 CondToken(Boolean doEval)
673 {
674 Token t;
675
676 if (condPushBack == None) {
677 while (*condExpr == ' ' || *condExpr == '\t') {
678 condExpr++;
679 }
680 switch (*condExpr) {
681 case '(':
682 t = LParen;
683 condExpr++;
684 break;
685 case ')':
686 t = RParen;
687 condExpr++;
688 break;
689 case '|':
690 if (condExpr[1] == '|') {
691 condExpr++;
692 }
693 condExpr++;
694 t = Or;
695 break;
696 case '&':
697 if (condExpr[1] == '&') {
698 condExpr++;
699 }
700 condExpr++;
701 t = And;
702 break;
703 case '!':
704 t = Not;
705 condExpr++;
706 break;
707 case '#':
708 case '\n':
709 case '\0':
710 t = EndOfFile;
711 break;
712 case '"':
713 case '$': {
714 char *lhs;
715 char *rhs;
716 char *op;
717 void *lhsFree;
718 void *rhsFree;
719 Boolean lhsQuoted;
720 Boolean rhsQuoted;
721
722 rhs = NULL;
723 lhsFree = rhsFree = FALSE;
724 lhsQuoted = rhsQuoted = FALSE;
725
726 /*
727 * Parse the variable spec and skip over it, saving its
728 * value in lhs.
729 */
730 t = Err;
731 lhs = CondGetString(doEval, &lhsQuoted, &lhsFree);
732 if (!lhs) {
733 if (lhsFree)
734 free(lhsFree);
735 return Err;
736 }
737 /*
738 * Skip whitespace to get to the operator
739 */
740 while (isspace((unsigned char) *condExpr))
741 condExpr++;
742
743 /*
744 * Make sure the operator is a valid one. If it isn't a
745 * known relational operator, pretend we got a
746 * != 0 comparison.
747 */
748 op = condExpr;
749 switch (*condExpr) {
750 case '!':
751 case '=':
752 case '<':
753 case '>':
754 if (condExpr[1] == '=') {
755 condExpr += 2;
756 } else {
757 condExpr += 1;
758 }
759 break;
760 default:
761 op = UNCONST("!=");
762 if (lhsQuoted)
763 rhs = UNCONST("");
764 else
765 rhs = UNCONST("0");
766
767 goto do_compare;
768 }
769 while (isspace((unsigned char) *condExpr)) {
770 condExpr++;
771 }
772 if (*condExpr == '\0') {
773 Parse_Error(PARSE_WARNING,
774 "Missing right-hand-side of operator");
775 goto error;
776 }
777 rhs = CondGetString(doEval, &rhsQuoted, &rhsFree);
778 if (!rhs) {
779 if (lhsFree)
780 free(lhsFree);
781 if (rhsFree)
782 free(rhsFree);
783 return Err;
784 }
785 do_compare:
786 if (rhsQuoted || lhsQuoted) {
787 do_string_compare:
788 if (((*op != '!') && (*op != '=')) || (op[1] != '=')) {
789 Parse_Error(PARSE_WARNING,
790 "String comparison operator should be either == or !=");
791 goto error;
792 }
793
794 if (DEBUG(COND)) {
795 fprintf(debug_file, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
796 lhs, rhs, op);
797 }
798 /*
799 * Null-terminate rhs and perform the comparison.
800 * t is set to the result.
801 */
802 if (*op == '=') {
803 t = strcmp(lhs, rhs) ? False : True;
804 } else {
805 t = strcmp(lhs, rhs) ? True : False;
806 }
807 } else {
808 /*
809 * rhs is either a float or an integer. Convert both the
810 * lhs and the rhs to a double and compare the two.
811 */
812 double left, right;
813 char *cp;
814
815 if (CondCvtArg(lhs, &left))
816 goto do_string_compare;
817 if ((cp = CondCvtArg(rhs, &right)) &&
818 cp == rhs)
819 goto do_string_compare;
820
821 if (DEBUG(COND)) {
822 fprintf(debug_file, "left = %f, right = %f, op = %.2s\n", left,
823 right, op);
824 }
825 switch(op[0]) {
826 case '!':
827 if (op[1] != '=') {
828 Parse_Error(PARSE_WARNING,
829 "Unknown operator");
830 goto error;
831 }
832 t = (left != right ? True : False);
833 break;
834 case '=':
835 if (op[1] != '=') {
836 Parse_Error(PARSE_WARNING,
837 "Unknown operator");
838 goto error;
839 }
840 t = (left == right ? True : False);
841 break;
842 case '<':
843 if (op[1] == '=') {
844 t = (left <= right ? True : False);
845 } else {
846 t = (left < right ? True : False);
847 }
848 break;
849 case '>':
850 if (op[1] == '=') {
851 t = (left >= right ? True : False);
852 } else {
853 t = (left > right ? True : False);
854 }
855 break;
856 }
857 }
858 error:
859 if (lhsFree)
860 free(lhsFree);
861 if (rhsFree)
862 free(rhsFree);
863 break;
864 }
865 default: {
866 Boolean (*evalProc)(int, char *);
867 Boolean invert = FALSE;
868 char *arg = NULL;
869 int arglen = 0;
870
871 if (istoken(condExpr, "defined", 7)) {
872 /*
873 * Use CondDoDefined to evaluate the argument and
874 * CondGetArg to extract the argument from the 'function
875 * call'.
876 */
877 evalProc = CondDoDefined;
878 condExpr += 7;
879 arglen = CondGetArg(&condExpr, &arg, "defined", TRUE);
880 if (arglen == 0) {
881 condExpr -= 7;
882 goto use_default;
883 }
884 } else if (istoken(condExpr, "make", 4)) {
885 /*
886 * Use CondDoMake to evaluate the argument and
887 * CondGetArg to extract the argument from the 'function
888 * call'.
889 */
890 evalProc = CondDoMake;
891 condExpr += 4;
892 arglen = CondGetArg(&condExpr, &arg, "make", TRUE);
893 if (arglen == 0) {
894 condExpr -= 4;
895 goto use_default;
896 }
897 } else if (istoken(condExpr, "exists", 6)) {
898 /*
899 * Use CondDoExists to evaluate the argument and
900 * CondGetArg to extract the argument from the
901 * 'function call'.
902 */
903 evalProc = CondDoExists;
904 condExpr += 6;
905 arglen = CondGetArg(&condExpr, &arg, "exists", TRUE);
906 if (arglen == 0) {
907 condExpr -= 6;
908 goto use_default;
909 }
910 } else if (istoken(condExpr, "empty", 5)) {
911 /*
912 * Use Var_Parse to parse the spec in parens and return
913 * True if the resulting string is empty.
914 */
915 int length;
916 void *freeIt;
917 char *val;
918
919 condExpr += 5;
920
921 for (arglen = 0;
922 condExpr[arglen] != '(' && condExpr[arglen] != '\0';
923 arglen += 1)
924 continue;
925
926 if (condExpr[arglen] != '\0') {
927 val = Var_Parse(&condExpr[arglen - 1], VAR_CMD,
928 FALSE, &length, &freeIt);
929 if (val == var_Error) {
930 t = Err;
931 } else {
932 /*
933 * A variable is empty when it just contains
934 * spaces... 4/15/92, christos
935 */
936 char *p;
937 for (p = val; *p && isspace((unsigned char)*p); p++)
938 continue;
939 t = (*p == '\0') ? True : False;
940 }
941 if (freeIt) {
942 free(freeIt);
943 }
944 /*
945 * Advance condExpr to beyond the closing ). Note that
946 * we subtract one from arglen + length b/c length
947 * is calculated from condExpr[arglen - 1].
948 */
949 condExpr += arglen + length - 1;
950 } else {
951 condExpr -= 5;
952 goto use_default;
953 }
954 break;
955 } else if (istoken(condExpr, "target", 6)) {
956 /*
957 * Use CondDoTarget to evaluate the argument and
958 * CondGetArg to extract the argument from the
959 * 'function call'.
960 */
961 evalProc = CondDoTarget;
962 condExpr += 6;
963 arglen = CondGetArg(&condExpr, &arg, "target", TRUE);
964 if (arglen == 0) {
965 condExpr -= 6;
966 goto use_default;
967 }
968 } else if (istoken(condExpr, "commands", 8)) {
969 /*
970 * Use CondDoCommands to evaluate the argument and
971 * CondGetArg to extract the argument from the
972 * 'function call'.
973 */
974 evalProc = CondDoCommands;
975 condExpr += 8;
976 arglen = CondGetArg(&condExpr, &arg, "commands", TRUE);
977 if (arglen == 0) {
978 condExpr -= 8;
979 goto use_default;
980 }
981 } else {
982 /*
983 * The symbol is itself the argument to the default
984 * function. We advance condExpr to the end of the symbol
985 * by hand (the next whitespace, closing paren or
986 * binary operator) and set to invert the evaluation
987 * function if condInvert is TRUE.
988 */
989 use_default:
990 invert = condInvert;
991 evalProc = condDefProc;
992 arglen = CondGetArg(&condExpr, &arg, "", FALSE);
993 }
994
995 /*
996 * Evaluate the argument using the set function. If invert
997 * is TRUE, we invert the sense of the function.
998 */
999 t = (!doEval || (* evalProc) (arglen, arg) ?
1000 (invert ? False : True) :
1001 (invert ? True : False));
1002 if (arg)
1003 free(arg);
1004 break;
1005 }
1006 }
1007 } else {
1008 t = condPushBack;
1009 condPushBack = None;
1010 }
1011 return (t);
1012 }
1013
1014 /*-
1016 *-----------------------------------------------------------------------
1017 * CondT --
1018 * Parse a single term in the expression. This consists of a terminal
1019 * symbol or Not and a terminal symbol (not including the binary
1020 * operators):
1021 * T -> defined(variable) | make(target) | exists(file) | symbol
1022 * T -> ! T | ( E )
1023 *
1024 * Results:
1025 * True, False or Err.
1026 *
1027 * Side Effects:
1028 * Tokens are consumed.
1029 *
1030 *-----------------------------------------------------------------------
1031 */
1032 static Token
1033 CondT(Boolean doEval)
1034 {
1035 Token t;
1036
1037 t = CondToken(doEval);
1038
1039 if (t == EndOfFile) {
1040 /*
1041 * If we reached the end of the expression, the expression
1042 * is malformed...
1043 */
1044 t = Err;
1045 } else if (t == LParen) {
1046 /*
1047 * T -> ( E )
1048 */
1049 t = CondE(doEval);
1050 if (t != Err) {
1051 if (CondToken(doEval) != RParen) {
1052 t = Err;
1053 }
1054 }
1055 } else if (t == Not) {
1056 t = CondT(doEval);
1057 if (t == True) {
1058 t = False;
1059 } else if (t == False) {
1060 t = True;
1061 }
1062 }
1063 return (t);
1064 }
1065
1066 /*-
1068 *-----------------------------------------------------------------------
1069 * CondF --
1070 * Parse a conjunctive factor (nice name, wot?)
1071 * F -> T && F | T
1072 *
1073 * Results:
1074 * True, False or Err
1075 *
1076 * Side Effects:
1077 * Tokens are consumed.
1078 *
1079 *-----------------------------------------------------------------------
1080 */
1081 static Token
1082 CondF(Boolean doEval)
1083 {
1084 Token l, o;
1085
1086 l = CondT(doEval);
1087 if (l != Err) {
1088 o = CondToken(doEval);
1089
1090 if (o == And) {
1091 /*
1092 * F -> T && F
1093 *
1094 * If T is False, the whole thing will be False, but we have to
1095 * parse the r.h.s. anyway (to throw it away).
1096 * If T is True, the result is the r.h.s., be it an Err or no.
1097 */
1098 if (l == True) {
1099 l = CondF(doEval);
1100 } else {
1101 (void)CondF(FALSE);
1102 }
1103 } else {
1104 /*
1105 * F -> T
1106 */
1107 CondPushBack(o);
1108 }
1109 }
1110 return (l);
1111 }
1112
1113 /*-
1115 *-----------------------------------------------------------------------
1116 * CondE --
1117 * Main expression production.
1118 * E -> F || E | F
1119 *
1120 * Results:
1121 * True, False or Err.
1122 *
1123 * Side Effects:
1124 * Tokens are, of course, consumed.
1125 *
1126 *-----------------------------------------------------------------------
1127 */
1128 static Token
1129 CondE(Boolean doEval)
1130 {
1131 Token l, o;
1132
1133 l = CondF(doEval);
1134 if (l != Err) {
1135 o = CondToken(doEval);
1136
1137 if (o == Or) {
1138 /*
1139 * E -> F || E
1140 *
1141 * A similar thing occurs for ||, except that here we make sure
1142 * the l.h.s. is False before we bother to evaluate the r.h.s.
1143 * Once again, if l is False, the result is the r.h.s. and once
1144 * again if l is True, we parse the r.h.s. to throw it away.
1145 */
1146 if (l == False) {
1147 l = CondE(doEval);
1148 } else {
1149 (void)CondE(FALSE);
1150 }
1151 } else {
1152 /*
1153 * E -> F
1154 */
1155 CondPushBack(o);
1156 }
1157 }
1158 return (l);
1159 }
1160
1161 /*-
1162 *-----------------------------------------------------------------------
1163 * Cond_EvalExpression --
1164 * Evaluate an expression in the passed line. The expression
1165 * consists of &&, ||, !, make(target), defined(variable)
1166 * and parenthetical groupings thereof.
1167 *
1168 * Results:
1169 * COND_PARSE if the condition was valid grammatically
1170 * COND_INVALID if not a valid conditional.
1171 *
1172 * (*value) is set to the boolean value of the condition
1173 *
1174 * Side Effects:
1175 * None.
1176 *
1177 *-----------------------------------------------------------------------
1178 */
1179 int
1180 Cond_EvalExpression(int dosetup, char *line, Boolean *value, int eprint)
1181 {
1182 if (dosetup) {
1183 condDefProc = CondDoDefined;
1184 condInvert = 0;
1185 }
1186
1187 while (*line == ' ' || *line == '\t')
1188 line++;
1189
1190 condExpr = line;
1191 condPushBack = None;
1192
1193 switch (CondE(TRUE)) {
1194 case True:
1195 if (CondToken(TRUE) == EndOfFile) {
1196 *value = TRUE;
1197 break;
1198 }
1199 goto err;
1200 /*FALLTHRU*/
1201 case False:
1202 if (CondToken(TRUE) == EndOfFile) {
1203 *value = FALSE;
1204 break;
1205 }
1206 /*FALLTHRU*/
1207 case Err:
1208 err:
1209 if (eprint)
1210 Parse_Error(PARSE_FATAL, "Malformed conditional (%s)",
1211 line);
1212 return (COND_INVALID);
1213 default:
1214 break;
1215 }
1216
1217 return COND_PARSE;
1218 }
1219
1220
1221 /*-
1223 *-----------------------------------------------------------------------
1224 * Cond_Eval --
1225 * Evaluate the conditional in the passed line. The line
1226 * looks like this:
1227 * .<cond-type> <expr>
1228 * where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1229 * ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1230 * and <expr> consists of &&, ||, !, make(target), defined(variable)
1231 * and parenthetical groupings thereof.
1232 *
1233 * Input:
1234 * line Line to parse
1235 *
1236 * Results:
1237 * COND_PARSE if should parse lines after the conditional
1238 * COND_SKIP if should skip lines after the conditional
1239 * COND_INVALID if not a valid conditional.
1240 *
1241 * Side Effects:
1242 * None.
1243 *
1244 * Note that the states IF_ACTIVE and ELSE_ACTIVE are only different in order
1245 * to detect splurious .else lines (as are SKIP_TO_ELSE and SKIP_TO_ENDIF)
1246 * otherwise .else could be treated as '.elif 1'.
1247 *
1248 *-----------------------------------------------------------------------
1249 */
1250 int
1251 Cond_Eval(char *line)
1252 {
1253 #define MAXIF 64 /* maximum depth of .if'ing */
1254 enum if_states {
1255 IF_ACTIVE, /* .if or .elif part active */
1256 ELSE_ACTIVE, /* .else part active */
1257 SEARCH_FOR_ELIF, /* searching for .elif/else to execute */
1258 SKIP_TO_ELSE, /* has been true, but not seen '.else' */
1259 SKIP_TO_ENDIF /* nothing else to execute */
1260 };
1261 static enum if_states cond_state[MAXIF + 1] = { IF_ACTIVE };
1262
1263 const struct If *ifp;
1264 Boolean isElif;
1265 Boolean value;
1266 int level; /* Level at which to report errors. */
1267 enum if_states state;
1268
1269 level = PARSE_FATAL;
1270
1271 /* skip leading character (the '.') and any whitespace */
1272 for (line++; *line == ' ' || *line == '\t'; line++)
1273 continue;
1274
1275 /* Find what type of if we're dealing with. */
1276 if (line[0] == 'e') {
1277 if (line[1] != 'l') {
1278 if (!istoken(line + 1, "ndif", 4))
1279 return COND_INVALID;
1280 /* End of conditional section */
1281 if (cond_depth == cond_min_depth) {
1282 Parse_Error(level, "if-less endif");
1283 return COND_PARSE;
1284 }
1285 /* Return state for previous conditional */
1286 cond_depth--;
1287 return cond_state[cond_depth] <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP;
1288 }
1289
1290 /* Quite likely this is 'else' or 'elif' */
1291 line += 2;
1292 if (istoken(line, "se", 2)) {
1293 /* It is else... */
1294 if (cond_depth == cond_min_depth) {
1295 Parse_Error(level, "if-less else");
1296 return COND_INVALID;
1297 }
1298
1299 state = cond_state[cond_depth];
1300 switch (state) {
1301 case SEARCH_FOR_ELIF:
1302 state = ELSE_ACTIVE;
1303 break;
1304 case ELSE_ACTIVE:
1305 case SKIP_TO_ENDIF:
1306 Parse_Error(PARSE_WARNING, "extra else");
1307 /* FALLTHROUGH */
1308 default:
1309 case IF_ACTIVE:
1310 case SKIP_TO_ELSE:
1311 state = SKIP_TO_ENDIF;
1312 break;
1313 }
1314 cond_state[cond_depth] = state;
1315 return state <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP;
1316 }
1317 /* Assume for now it is an elif */
1318 isElif = TRUE;
1319 } else
1320 isElif = FALSE;
1321
1322 if (line[0] != 'i' || line[1] != 'f')
1323 /* Not an ifxxx or elifxxx line */
1324 return COND_INVALID;
1325
1326 /*
1327 * Figure out what sort of conditional it is -- what its default
1328 * function is, etc. -- by looking in the table of valid "ifs"
1329 */
1330 line += 2;
1331 for (ifp = ifs; ; ifp++) {
1332 if (ifp->form == NULL)
1333 return COND_INVALID;
1334 if (istoken(ifp->form, line, ifp->formlen)) {
1335 line += ifp->formlen;
1336 break;
1337 }
1338 }
1339
1340 /* Now we know what sort of 'if' it is... */
1341 state = cond_state[cond_depth];
1342
1343 if (isElif) {
1344 if (cond_depth == cond_min_depth) {
1345 Parse_Error(level, "if-less elif");
1346 return COND_INVALID;
1347 }
1348 if (state == SKIP_TO_ENDIF || state == ELSE_ACTIVE)
1349 Parse_Error(PARSE_WARNING, "extra elif");
1350 if (state != SEARCH_FOR_ELIF) {
1351 /* Either just finished the 'true' block, or already SKIP_TO_ELSE */
1352 cond_state[cond_depth] = SKIP_TO_ELSE;
1353 return COND_SKIP;
1354 }
1355 } else {
1356 if (cond_depth >= MAXIF) {
1357 Parse_Error(PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
1358 return COND_INVALID;
1359 }
1360 cond_depth++;
1361 if (state > ELSE_ACTIVE) {
1362 /* If we aren't parsing the data, treat as always false */
1363 cond_state[cond_depth] = SKIP_TO_ELSE;
1364 return COND_SKIP;
1365 }
1366 }
1367
1368 /* Initialize file-global variables for parsing the expression */
1369 condDefProc = ifp->defProc;
1370 condInvert = ifp->doNot;
1371
1372 /* And evaluate the conditional expresssion */
1373 if (Cond_EvalExpression(0, line, &value, 1) == COND_INVALID) {
1374 /* Although we get make to reprocess the line, set a state */
1375 cond_state[cond_depth] = SEARCH_FOR_ELIF;
1376 return COND_INVALID;
1377 }
1378
1379 if (!value) {
1380 cond_state[cond_depth] = SEARCH_FOR_ELIF;
1381 return COND_SKIP;
1382 }
1383 cond_state[cond_depth] = IF_ACTIVE;
1384 return COND_PARSE;
1385 }
1386
1387
1388
1389 /*-
1391 *-----------------------------------------------------------------------
1392 * Cond_End --
1393 * Make sure everything's clean at the end of a makefile.
1394 *
1395 * Results:
1396 * None.
1397 *
1398 * Side Effects:
1399 * Parse_Error will be called if open conditionals are around.
1400 *
1401 *-----------------------------------------------------------------------
1402 */
1403 void
1404 Cond_restore_depth(unsigned int saved_depth)
1405 {
1406 int open_conds = cond_depth - cond_min_depth;
1407
1408 if (open_conds != 0 || saved_depth > cond_depth) {
1409 Parse_Error(PARSE_FATAL, "%d open conditional%s", open_conds,
1410 open_conds == 1 ? "" : "s");
1411 cond_depth = cond_min_depth;
1412 }
1413
1414 cond_min_depth = saved_depth;
1415 }
1416
1417 unsigned int
1418 Cond_save_depth(void)
1419 {
1420 int depth = cond_min_depth;
1421
1422 cond_min_depth = cond_depth;
1423 return depth;
1424 }
1425