cond.c revision 1.43 1 /* $NetBSD: cond.c,v 1.43 2008/11/22 18:05:13 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.43 2008/11/22 18:05:13 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.43 2008/11/22 18:05:13 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 do_compare_setup:
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 fprintf(debug_file, "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 fprintf(debug_file, "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 did_warn, length;
918 void *freeIt;
919 char *val;
920
921 condExpr += 5;
922
923 did_warn = 0;
924 for (arglen = 0; condExpr[arglen] != '\0'; arglen += 1) {
925 if (condExpr[arglen] == '(')
926 break;
927 if (!isspace((unsigned char)condExpr[arglen]) &&
928 !did_warn) {
929
930 Parse_Error(PARSE_WARNING,
931 "Extra characters after \"empty\"");
932 did_warn = 1;
933 }
934 }
935
936 if (condExpr[arglen] != '\0') {
937 val = Var_Parse(&condExpr[arglen - 1], VAR_CMD,
938 FALSE, &length, &freeIt);
939 if (val == var_Error) {
940 t = Err;
941 } else {
942 /*
943 * A variable is empty when it just contains
944 * spaces... 4/15/92, christos
945 */
946 char *p;
947 for (p = val; *p && isspace((unsigned char)*p); p++)
948 continue;
949 t = (*p == '\0') ? True : False;
950 }
951 if (freeIt) {
952 free(freeIt);
953 }
954 /*
955 * Advance condExpr to beyond the closing ). Note that
956 * we subtract one from arglen + length b/c length
957 * is calculated from condExpr[arglen - 1].
958 */
959 condExpr += arglen + length - 1;
960 } else {
961 condExpr -= 5;
962 goto use_default;
963 }
964 break;
965 } else if (istoken(condExpr, "target", 6)) {
966 /*
967 * Use CondDoTarget to evaluate the argument and
968 * CondGetArg to extract the argument from the
969 * 'function call'.
970 */
971 evalProc = CondDoTarget;
972 condExpr += 6;
973 arglen = CondGetArg(&condExpr, &arg, "target", TRUE);
974 if (arglen == 0) {
975 condExpr -= 6;
976 goto use_default;
977 }
978 } else if (istoken(condExpr, "commands", 8)) {
979 /*
980 * Use CondDoCommands to evaluate the argument and
981 * CondGetArg to extract the argument from the
982 * 'function call'.
983 */
984 evalProc = CondDoCommands;
985 condExpr += 8;
986 arglen = CondGetArg(&condExpr, &arg, "commands", TRUE);
987 if (arglen == 0) {
988 condExpr -= 8;
989 goto use_default;
990 }
991 } else {
992 /*
993 * The symbol is itself the argument to the default
994 * function. We advance condExpr to the end of the symbol
995 * by hand (the next whitespace, closing paren or
996 * binary operator) and set to invert the evaluation
997 * function if condInvert is TRUE.
998 */
999 if (isdigit((unsigned char)condExpr[0])) {
1000 /*
1001 * Variables may already be substituted
1002 * by the time we get here.
1003 */
1004 goto do_compare_setup;
1005 }
1006 use_default:
1007 invert = condInvert;
1008 evalProc = condDefProc;
1009 arglen = CondGetArg(&condExpr, &arg, "", FALSE);
1010 }
1011
1012 /*
1013 * Evaluate the argument using the set function. If invert
1014 * is TRUE, we invert the sense of the function.
1015 */
1016 t = (!doEval || (* evalProc) (arglen, arg) ?
1017 (invert ? False : True) :
1018 (invert ? True : False));
1019 if (arg)
1020 free(arg);
1021 break;
1022 }
1023 }
1024 } else {
1025 t = condPushBack;
1026 condPushBack = None;
1027 }
1028 return (t);
1029 }
1030
1031 /*-
1033 *-----------------------------------------------------------------------
1034 * CondT --
1035 * Parse a single term in the expression. This consists of a terminal
1036 * symbol or Not and a terminal symbol (not including the binary
1037 * operators):
1038 * T -> defined(variable) | make(target) | exists(file) | symbol
1039 * T -> ! T | ( E )
1040 *
1041 * Results:
1042 * True, False or Err.
1043 *
1044 * Side Effects:
1045 * Tokens are consumed.
1046 *
1047 *-----------------------------------------------------------------------
1048 */
1049 static Token
1050 CondT(Boolean doEval)
1051 {
1052 Token t;
1053
1054 t = CondToken(doEval);
1055
1056 if (t == EndOfFile) {
1057 /*
1058 * If we reached the end of the expression, the expression
1059 * is malformed...
1060 */
1061 t = Err;
1062 } else if (t == LParen) {
1063 /*
1064 * T -> ( E )
1065 */
1066 t = CondE(doEval);
1067 if (t != Err) {
1068 if (CondToken(doEval) != RParen) {
1069 t = Err;
1070 }
1071 }
1072 } else if (t == Not) {
1073 t = CondT(doEval);
1074 if (t == True) {
1075 t = False;
1076 } else if (t == False) {
1077 t = True;
1078 }
1079 }
1080 return (t);
1081 }
1082
1083 /*-
1085 *-----------------------------------------------------------------------
1086 * CondF --
1087 * Parse a conjunctive factor (nice name, wot?)
1088 * F -> T && F | T
1089 *
1090 * Results:
1091 * True, False or Err
1092 *
1093 * Side Effects:
1094 * Tokens are consumed.
1095 *
1096 *-----------------------------------------------------------------------
1097 */
1098 static Token
1099 CondF(Boolean doEval)
1100 {
1101 Token l, o;
1102
1103 l = CondT(doEval);
1104 if (l != Err) {
1105 o = CondToken(doEval);
1106
1107 if (o == And) {
1108 /*
1109 * F -> T && F
1110 *
1111 * If T is False, the whole thing will be False, but we have to
1112 * parse the r.h.s. anyway (to throw it away).
1113 * If T is True, the result is the r.h.s., be it an Err or no.
1114 */
1115 if (l == True) {
1116 l = CondF(doEval);
1117 } else {
1118 (void)CondF(FALSE);
1119 }
1120 } else {
1121 /*
1122 * F -> T
1123 */
1124 CondPushBack(o);
1125 }
1126 }
1127 return (l);
1128 }
1129
1130 /*-
1132 *-----------------------------------------------------------------------
1133 * CondE --
1134 * Main expression production.
1135 * E -> F || E | F
1136 *
1137 * Results:
1138 * True, False or Err.
1139 *
1140 * Side Effects:
1141 * Tokens are, of course, consumed.
1142 *
1143 *-----------------------------------------------------------------------
1144 */
1145 static Token
1146 CondE(Boolean doEval)
1147 {
1148 Token l, o;
1149
1150 l = CondF(doEval);
1151 if (l != Err) {
1152 o = CondToken(doEval);
1153
1154 if (o == Or) {
1155 /*
1156 * E -> F || E
1157 *
1158 * A similar thing occurs for ||, except that here we make sure
1159 * the l.h.s. is False before we bother to evaluate the r.h.s.
1160 * Once again, if l is False, the result is the r.h.s. and once
1161 * again if l is True, we parse the r.h.s. to throw it away.
1162 */
1163 if (l == False) {
1164 l = CondE(doEval);
1165 } else {
1166 (void)CondE(FALSE);
1167 }
1168 } else {
1169 /*
1170 * E -> F
1171 */
1172 CondPushBack(o);
1173 }
1174 }
1175 return (l);
1176 }
1177
1178 /*-
1179 *-----------------------------------------------------------------------
1180 * Cond_EvalExpression --
1181 * Evaluate an expression in the passed line. The expression
1182 * consists of &&, ||, !, make(target), defined(variable)
1183 * and parenthetical groupings thereof.
1184 *
1185 * Results:
1186 * COND_PARSE if the condition was valid grammatically
1187 * COND_INVALID if not a valid conditional.
1188 *
1189 * (*value) is set to the boolean value of the condition
1190 *
1191 * Side Effects:
1192 * None.
1193 *
1194 *-----------------------------------------------------------------------
1195 */
1196 int
1197 Cond_EvalExpression(int dosetup, char *line, Boolean *value, int eprint)
1198 {
1199 if (dosetup) {
1200 condDefProc = CondDoDefined;
1201 condInvert = 0;
1202 }
1203
1204 while (*line == ' ' || *line == '\t')
1205 line++;
1206
1207 condExpr = line;
1208 condPushBack = None;
1209
1210 switch (CondE(TRUE)) {
1211 case True:
1212 if (CondToken(TRUE) == EndOfFile) {
1213 *value = TRUE;
1214 break;
1215 }
1216 goto err;
1217 /*FALLTHRU*/
1218 case False:
1219 if (CondToken(TRUE) == EndOfFile) {
1220 *value = FALSE;
1221 break;
1222 }
1223 /*FALLTHRU*/
1224 case Err:
1225 err:
1226 if (eprint)
1227 Parse_Error(PARSE_FATAL, "Malformed conditional (%s)",
1228 line);
1229 return (COND_INVALID);
1230 default:
1231 break;
1232 }
1233
1234 return COND_PARSE;
1235 }
1236
1237
1238 /*-
1240 *-----------------------------------------------------------------------
1241 * Cond_Eval --
1242 * Evaluate the conditional in the passed line. The line
1243 * looks like this:
1244 * .<cond-type> <expr>
1245 * where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1246 * ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1247 * and <expr> consists of &&, ||, !, make(target), defined(variable)
1248 * and parenthetical groupings thereof.
1249 *
1250 * Input:
1251 * line Line to parse
1252 *
1253 * Results:
1254 * COND_PARSE if should parse lines after the conditional
1255 * COND_SKIP if should skip lines after the conditional
1256 * COND_INVALID if not a valid conditional.
1257 *
1258 * Side Effects:
1259 * None.
1260 *
1261 * Note that the states IF_ACTIVE and ELSE_ACTIVE are only different in order
1262 * to detect splurious .else lines (as are SKIP_TO_ELSE and SKIP_TO_ENDIF)
1263 * otherwise .else could be treated as '.elif 1'.
1264 *
1265 *-----------------------------------------------------------------------
1266 */
1267 int
1268 Cond_Eval(char *line)
1269 {
1270 #define MAXIF 64 /* maximum depth of .if'ing */
1271 enum if_states {
1272 IF_ACTIVE, /* .if or .elif part active */
1273 ELSE_ACTIVE, /* .else part active */
1274 SEARCH_FOR_ELIF, /* searching for .elif/else to execute */
1275 SKIP_TO_ELSE, /* has been true, but not seen '.else' */
1276 SKIP_TO_ENDIF /* nothing else to execute */
1277 };
1278 static enum if_states cond_state[MAXIF + 1] = { IF_ACTIVE };
1279
1280 const struct If *ifp;
1281 Boolean isElif;
1282 Boolean value;
1283 int level; /* Level at which to report errors. */
1284 enum if_states state;
1285
1286 level = PARSE_FATAL;
1287
1288 /* skip leading character (the '.') and any whitespace */
1289 for (line++; *line == ' ' || *line == '\t'; line++)
1290 continue;
1291
1292 /* Find what type of if we're dealing with. */
1293 if (line[0] == 'e') {
1294 if (line[1] != 'l') {
1295 if (!istoken(line + 1, "ndif", 4))
1296 return COND_INVALID;
1297 /* End of conditional section */
1298 if (cond_depth == cond_min_depth) {
1299 Parse_Error(level, "if-less endif");
1300 return COND_PARSE;
1301 }
1302 /* Return state for previous conditional */
1303 cond_depth--;
1304 if (cond_depth > MAXIF)
1305 return COND_SKIP;
1306 return cond_state[cond_depth] <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP;
1307 }
1308
1309 /* Quite likely this is 'else' or 'elif' */
1310 line += 2;
1311 if (istoken(line, "se", 2)) {
1312 /* It is else... */
1313 if (cond_depth == cond_min_depth) {
1314 Parse_Error(level, "if-less else");
1315 return COND_PARSE;
1316 }
1317
1318 if (cond_depth > MAXIF)
1319 return COND_SKIP;
1320 state = cond_state[cond_depth];
1321 switch (state) {
1322 case SEARCH_FOR_ELIF:
1323 state = ELSE_ACTIVE;
1324 break;
1325 case ELSE_ACTIVE:
1326 case SKIP_TO_ENDIF:
1327 Parse_Error(PARSE_WARNING, "extra else");
1328 /* FALLTHROUGH */
1329 default:
1330 case IF_ACTIVE:
1331 case SKIP_TO_ELSE:
1332 state = SKIP_TO_ENDIF;
1333 break;
1334 }
1335 cond_state[cond_depth] = state;
1336 return state <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP;
1337 }
1338 /* Assume for now it is an elif */
1339 isElif = TRUE;
1340 } else
1341 isElif = FALSE;
1342
1343 if (line[0] != 'i' || line[1] != 'f')
1344 /* Not an ifxxx or elifxxx line */
1345 return COND_INVALID;
1346
1347 /*
1348 * Figure out what sort of conditional it is -- what its default
1349 * function is, etc. -- by looking in the table of valid "ifs"
1350 */
1351 line += 2;
1352 for (ifp = ifs; ; ifp++) {
1353 if (ifp->form == NULL)
1354 return COND_INVALID;
1355 if (istoken(ifp->form, line, ifp->formlen)) {
1356 line += ifp->formlen;
1357 break;
1358 }
1359 }
1360
1361 /* Now we know what sort of 'if' it is... */
1362
1363 if (isElif) {
1364 if (cond_depth == cond_min_depth) {
1365 Parse_Error(level, "if-less elif");
1366 return COND_PARSE;
1367 }
1368 if (cond_depth > MAXIF)
1369 /* Error reported when we saw the .if ... */
1370 return COND_SKIP;
1371 state = cond_state[cond_depth];
1372 if (state == SKIP_TO_ENDIF || state == ELSE_ACTIVE) {
1373 Parse_Error(PARSE_WARNING, "extra elif");
1374 cond_state[cond_depth] = SKIP_TO_ENDIF;
1375 return COND_SKIP;
1376 }
1377 if (state != SEARCH_FOR_ELIF) {
1378 /* Either just finished the 'true' block, or already SKIP_TO_ELSE */
1379 cond_state[cond_depth] = SKIP_TO_ELSE;
1380 return COND_SKIP;
1381 }
1382 } else {
1383 /* Normal .if */
1384 if (cond_depth >= MAXIF) {
1385 cond_depth++;
1386 Parse_Error(PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
1387 return COND_SKIP;
1388 }
1389 state = cond_state[cond_depth];
1390 cond_depth++;
1391 if (state > ELSE_ACTIVE) {
1392 /* If we aren't parsing the data, treat as always false */
1393 cond_state[cond_depth] = SKIP_TO_ELSE;
1394 return COND_SKIP;
1395 }
1396 }
1397
1398 /* Initialize file-global variables for parsing the expression */
1399 condDefProc = ifp->defProc;
1400 condInvert = ifp->doNot;
1401
1402 /* And evaluate the conditional expresssion */
1403 if (Cond_EvalExpression(0, line, &value, 1) == COND_INVALID) {
1404 /* Syntax error in conditional, error message already output. */
1405 /* Skip everything to matching .endif */
1406 cond_state[cond_depth] = SKIP_TO_ELSE;
1407 return COND_SKIP;
1408 }
1409
1410 if (!value) {
1411 cond_state[cond_depth] = SEARCH_FOR_ELIF;
1412 return COND_SKIP;
1413 }
1414 cond_state[cond_depth] = IF_ACTIVE;
1415 return COND_PARSE;
1416 }
1417
1418
1419
1420 /*-
1422 *-----------------------------------------------------------------------
1423 * Cond_End --
1424 * Make sure everything's clean at the end of a makefile.
1425 *
1426 * Results:
1427 * None.
1428 *
1429 * Side Effects:
1430 * Parse_Error will be called if open conditionals are around.
1431 *
1432 *-----------------------------------------------------------------------
1433 */
1434 void
1435 Cond_restore_depth(unsigned int saved_depth)
1436 {
1437 int open_conds = cond_depth - cond_min_depth;
1438
1439 if (open_conds != 0 || saved_depth > cond_depth) {
1440 Parse_Error(PARSE_FATAL, "%d open conditional%s", open_conds,
1441 open_conds == 1 ? "" : "s");
1442 cond_depth = cond_min_depth;
1443 }
1444
1445 cond_min_depth = saved_depth;
1446 }
1447
1448 unsigned int
1449 Cond_save_depth(void)
1450 {
1451 int depth = cond_min_depth;
1452
1453 cond_min_depth = cond_depth;
1454 return depth;
1455 }
1456