cond.c revision 1.40 1 /* $NetBSD: cond.c,v 1.40 2008/02/14 22:11:20 christos Exp $ */
2
3 /*
4 * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Adam de Boor.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35 /*
36 * Copyright (c) 1988, 1989 by Adam de Boor
37 * Copyright (c) 1989 by Berkeley Softworks
38 * All rights reserved.
39 *
40 * This code is derived from software contributed to Berkeley by
41 * Adam de Boor.
42 *
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
45 * are met:
46 * 1. Redistributions of source code must retain the above copyright
47 * notice, this list of conditions and the following disclaimer.
48 * 2. Redistributions in binary form must reproduce the above copyright
49 * notice, this list of conditions and the following disclaimer in the
50 * documentation and/or other materials provided with the distribution.
51 * 3. All advertising materials mentioning features or use of this software
52 * must display the following acknowledgement:
53 * This product includes software developed by the University of
54 * California, Berkeley and its contributors.
55 * 4. Neither the name of the University nor the names of its contributors
56 * may be used to endorse or promote products derived from this software
57 * without specific prior written permission.
58 *
59 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69 * SUCH DAMAGE.
70 */
71
72 #ifndef MAKE_NATIVE
73 static char rcsid[] = "$NetBSD: cond.c,v 1.40 2008/02/14 22:11:20 christos Exp $";
74 #else
75 #include <sys/cdefs.h>
76 #ifndef lint
77 #if 0
78 static char sccsid[] = "@(#)cond.c 8.2 (Berkeley) 1/2/94";
79 #else
80 __RCSID("$NetBSD: cond.c,v 1.40 2008/02/14 22:11:20 christos Exp $");
81 #endif
82 #endif /* not lint */
83 #endif
84
85 /*-
86 * cond.c --
87 * Functions to handle conditionals in a makefile.
88 *
89 * Interface:
90 * Cond_Eval Evaluate the conditional in the passed line.
91 *
92 */
93
94 #include <ctype.h>
95
96 #include "make.h"
97 #include "hash.h"
98 #include "dir.h"
99 #include "buf.h"
100
101 /*
102 * The parsing of conditional expressions is based on this grammar:
103 * E -> F || E
104 * E -> F
105 * F -> T && F
106 * F -> T
107 * T -> defined(variable)
108 * T -> make(target)
109 * T -> exists(file)
110 * T -> empty(varspec)
111 * T -> target(name)
112 * T -> commands(name)
113 * T -> symbol
114 * T -> $(varspec) op value
115 * T -> $(varspec) == "string"
116 * T -> $(varspec) != "string"
117 * T -> "string"
118 * T -> ( E )
119 * T -> ! T
120 * op -> == | != | > | < | >= | <=
121 *
122 * 'symbol' is some other symbol to which the default function (condDefProc)
123 * is applied.
124 *
125 * Tokens are scanned from the 'condExpr' string. The scanner (CondToken)
126 * will return And for '&' and '&&', Or for '|' and '||', Not for '!',
127 * LParen for '(', RParen for ')' and will evaluate the other terminal
128 * symbols, using either the default function or the function given in the
129 * terminal, and return the result as either True or False.
130 *
131 * All Non-Terminal functions (CondE, CondF and CondT) return Err on error.
132 */
133 typedef enum {
134 And, Or, Not, True, False, LParen, RParen, EndOfFile, None, Err
135 } Token;
136
137 /*-
138 * Structures to handle elegantly the different forms of #if's. The
139 * last two fields are stored in condInvert and condDefProc, respectively.
140 */
141 static void CondPushBack(Token);
142 static int CondGetArg(char **, char **, const char *, Boolean);
143 static Boolean CondDoDefined(int, char *);
144 static int CondStrMatch(ClientData, ClientData);
145 static Boolean CondDoMake(int, char *);
146 static Boolean CondDoExists(int, char *);
147 static Boolean CondDoTarget(int, char *);
148 static Boolean CondDoCommands(int, char *);
149 static char * CondCvtArg(char *, double *);
150 static Token CondToken(Boolean);
151 static Token CondT(Boolean);
152 static Token CondF(Boolean);
153 static Token CondE(Boolean);
154
155 static const struct If {
156 const char *form; /* Form of if */
157 size_t 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 size_t 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 size_t 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 size_t 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 did_warn;
916 size_t length;
917 void *freeIt;
918 char *val;
919
920 condExpr += 5;
921
922 did_warn = 0;
923 for (arglen = 0; condExpr[arglen] != '\0'; arglen += 1) {
924 if (condExpr[arglen] == '(')
925 break;
926 if (!isspace((unsigned char)condExpr[arglen]) &&
927 !did_warn) {
928
929 Parse_Error(PARSE_WARNING,
930 "Extra characters after \"empty\"");
931 did_warn = 1;
932 }
933 }
934
935 if (condExpr[arglen] != '\0') {
936 val = Var_Parse(&condExpr[arglen - 1], VAR_CMD,
937 FALSE, &length, &freeIt);
938 if (val == var_Error) {
939 t = Err;
940 } else {
941 /*
942 * A variable is empty when it just contains
943 * spaces... 4/15/92, christos
944 */
945 char *p;
946 for (p = val; *p && isspace((unsigned char)*p); p++)
947 continue;
948 t = (*p == '\0') ? True : False;
949 }
950 if (freeIt) {
951 free(freeIt);
952 }
953 /*
954 * Advance condExpr to beyond the closing ). Note that
955 * we subtract one from arglen + length b/c length
956 * is calculated from condExpr[arglen - 1].
957 */
958 condExpr += arglen + length - 1;
959 } else {
960 condExpr -= 5;
961 goto use_default;
962 }
963 break;
964 } else if (istoken(condExpr, "target", 6)) {
965 /*
966 * Use CondDoTarget to evaluate the argument and
967 * CondGetArg to extract the argument from the
968 * 'function call'.
969 */
970 evalProc = CondDoTarget;
971 condExpr += 6;
972 arglen = CondGetArg(&condExpr, &arg, "target", TRUE);
973 if (arglen == 0) {
974 condExpr -= 6;
975 goto use_default;
976 }
977 } else if (istoken(condExpr, "commands", 8)) {
978 /*
979 * Use CondDoCommands to evaluate the argument and
980 * CondGetArg to extract the argument from the
981 * 'function call'.
982 */
983 evalProc = CondDoCommands;
984 condExpr += 8;
985 arglen = CondGetArg(&condExpr, &arg, "commands", TRUE);
986 if (arglen == 0) {
987 condExpr -= 8;
988 goto use_default;
989 }
990 } else {
991 /*
992 * The symbol is itself the argument to the default
993 * function. We advance condExpr to the end of the symbol
994 * by hand (the next whitespace, closing paren or
995 * binary operator) and set to invert the evaluation
996 * function if condInvert is TRUE.
997 */
998 use_default:
999 invert = condInvert;
1000 evalProc = condDefProc;
1001 arglen = CondGetArg(&condExpr, &arg, "", FALSE);
1002 }
1003
1004 /*
1005 * Evaluate the argument using the set function. If invert
1006 * is TRUE, we invert the sense of the function.
1007 */
1008 t = (!doEval || (* evalProc) (arglen, arg) ?
1009 (invert ? False : True) :
1010 (invert ? True : False));
1011 if (arg)
1012 free(arg);
1013 break;
1014 }
1015 }
1016 } else {
1017 t = condPushBack;
1018 condPushBack = None;
1019 }
1020 return (t);
1021 }
1022
1023 /*-
1025 *-----------------------------------------------------------------------
1026 * CondT --
1027 * Parse a single term in the expression. This consists of a terminal
1028 * symbol or Not and a terminal symbol (not including the binary
1029 * operators):
1030 * T -> defined(variable) | make(target) | exists(file) | symbol
1031 * T -> ! T | ( E )
1032 *
1033 * Results:
1034 * True, False or Err.
1035 *
1036 * Side Effects:
1037 * Tokens are consumed.
1038 *
1039 *-----------------------------------------------------------------------
1040 */
1041 static Token
1042 CondT(Boolean doEval)
1043 {
1044 Token t;
1045
1046 t = CondToken(doEval);
1047
1048 if (t == EndOfFile) {
1049 /*
1050 * If we reached the end of the expression, the expression
1051 * is malformed...
1052 */
1053 t = Err;
1054 } else if (t == LParen) {
1055 /*
1056 * T -> ( E )
1057 */
1058 t = CondE(doEval);
1059 if (t != Err) {
1060 if (CondToken(doEval) != RParen) {
1061 t = Err;
1062 }
1063 }
1064 } else if (t == Not) {
1065 t = CondT(doEval);
1066 if (t == True) {
1067 t = False;
1068 } else if (t == False) {
1069 t = True;
1070 }
1071 }
1072 return (t);
1073 }
1074
1075 /*-
1077 *-----------------------------------------------------------------------
1078 * CondF --
1079 * Parse a conjunctive factor (nice name, wot?)
1080 * F -> T && F | T
1081 *
1082 * Results:
1083 * True, False or Err
1084 *
1085 * Side Effects:
1086 * Tokens are consumed.
1087 *
1088 *-----------------------------------------------------------------------
1089 */
1090 static Token
1091 CondF(Boolean doEval)
1092 {
1093 Token l, o;
1094
1095 l = CondT(doEval);
1096 if (l != Err) {
1097 o = CondToken(doEval);
1098
1099 if (o == And) {
1100 /*
1101 * F -> T && F
1102 *
1103 * If T is False, the whole thing will be False, but we have to
1104 * parse the r.h.s. anyway (to throw it away).
1105 * If T is True, the result is the r.h.s., be it an Err or no.
1106 */
1107 if (l == True) {
1108 l = CondF(doEval);
1109 } else {
1110 (void)CondF(FALSE);
1111 }
1112 } else {
1113 /*
1114 * F -> T
1115 */
1116 CondPushBack(o);
1117 }
1118 }
1119 return (l);
1120 }
1121
1122 /*-
1124 *-----------------------------------------------------------------------
1125 * CondE --
1126 * Main expression production.
1127 * E -> F || E | F
1128 *
1129 * Results:
1130 * True, False or Err.
1131 *
1132 * Side Effects:
1133 * Tokens are, of course, consumed.
1134 *
1135 *-----------------------------------------------------------------------
1136 */
1137 static Token
1138 CondE(Boolean doEval)
1139 {
1140 Token l, o;
1141
1142 l = CondF(doEval);
1143 if (l != Err) {
1144 o = CondToken(doEval);
1145
1146 if (o == Or) {
1147 /*
1148 * E -> F || E
1149 *
1150 * A similar thing occurs for ||, except that here we make sure
1151 * the l.h.s. is False before we bother to evaluate the r.h.s.
1152 * Once again, if l is False, the result is the r.h.s. and once
1153 * again if l is True, we parse the r.h.s. to throw it away.
1154 */
1155 if (l == False) {
1156 l = CondE(doEval);
1157 } else {
1158 (void)CondE(FALSE);
1159 }
1160 } else {
1161 /*
1162 * E -> F
1163 */
1164 CondPushBack(o);
1165 }
1166 }
1167 return (l);
1168 }
1169
1170 /*-
1171 *-----------------------------------------------------------------------
1172 * Cond_EvalExpression --
1173 * Evaluate an expression in the passed line. The expression
1174 * consists of &&, ||, !, make(target), defined(variable)
1175 * and parenthetical groupings thereof.
1176 *
1177 * Results:
1178 * COND_PARSE if the condition was valid grammatically
1179 * COND_INVALID if not a valid conditional.
1180 *
1181 * (*value) is set to the boolean value of the condition
1182 *
1183 * Side Effects:
1184 * None.
1185 *
1186 *-----------------------------------------------------------------------
1187 */
1188 int
1189 Cond_EvalExpression(int dosetup, char *line, Boolean *value, int eprint)
1190 {
1191 if (dosetup) {
1192 condDefProc = CondDoDefined;
1193 condInvert = 0;
1194 }
1195
1196 while (*line == ' ' || *line == '\t')
1197 line++;
1198
1199 condExpr = line;
1200 condPushBack = None;
1201
1202 switch (CondE(TRUE)) {
1203 case True:
1204 if (CondToken(TRUE) == EndOfFile) {
1205 *value = TRUE;
1206 break;
1207 }
1208 goto err;
1209 /*FALLTHRU*/
1210 case False:
1211 if (CondToken(TRUE) == EndOfFile) {
1212 *value = FALSE;
1213 break;
1214 }
1215 /*FALLTHRU*/
1216 case Err:
1217 err:
1218 if (eprint)
1219 Parse_Error(PARSE_FATAL, "Malformed conditional (%s)",
1220 line);
1221 return (COND_INVALID);
1222 default:
1223 break;
1224 }
1225
1226 return COND_PARSE;
1227 }
1228
1229
1230 /*-
1232 *-----------------------------------------------------------------------
1233 * Cond_Eval --
1234 * Evaluate the conditional in the passed line. The line
1235 * looks like this:
1236 * .<cond-type> <expr>
1237 * where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1238 * ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1239 * and <expr> consists of &&, ||, !, make(target), defined(variable)
1240 * and parenthetical groupings thereof.
1241 *
1242 * Input:
1243 * line Line to parse
1244 *
1245 * Results:
1246 * COND_PARSE if should parse lines after the conditional
1247 * COND_SKIP if should skip lines after the conditional
1248 * COND_INVALID if not a valid conditional.
1249 *
1250 * Side Effects:
1251 * None.
1252 *
1253 * Note that the states IF_ACTIVE and ELSE_ACTIVE are only different in order
1254 * to detect splurious .else lines (as are SKIP_TO_ELSE and SKIP_TO_ENDIF)
1255 * otherwise .else could be treated as '.elif 1'.
1256 *
1257 *-----------------------------------------------------------------------
1258 */
1259 int
1260 Cond_Eval(char *line)
1261 {
1262 #define MAXIF 64 /* maximum depth of .if'ing */
1263 enum if_states {
1264 IF_ACTIVE, /* .if or .elif part active */
1265 ELSE_ACTIVE, /* .else part active */
1266 SEARCH_FOR_ELIF, /* searching for .elif/else to execute */
1267 SKIP_TO_ELSE, /* has been true, but not seen '.else' */
1268 SKIP_TO_ENDIF /* nothing else to execute */
1269 };
1270 static enum if_states cond_state[MAXIF + 1] = { IF_ACTIVE };
1271
1272 const struct If *ifp;
1273 Boolean isElif;
1274 Boolean value;
1275 int level; /* Level at which to report errors. */
1276 enum if_states state;
1277
1278 level = PARSE_FATAL;
1279
1280 /* skip leading character (the '.') and any whitespace */
1281 for (line++; *line == ' ' || *line == '\t'; line++)
1282 continue;
1283
1284 /* Find what type of if we're dealing with. */
1285 if (line[0] == 'e') {
1286 if (line[1] != 'l') {
1287 if (!istoken(line + 1, "ndif", 4))
1288 return COND_INVALID;
1289 /* End of conditional section */
1290 if (cond_depth == cond_min_depth) {
1291 Parse_Error(level, "if-less endif");
1292 return COND_PARSE;
1293 }
1294 /* Return state for previous conditional */
1295 cond_depth--;
1296 return cond_state[cond_depth] <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP;
1297 }
1298
1299 /* Quite likely this is 'else' or 'elif' */
1300 line += 2;
1301 if (istoken(line, "se", 2)) {
1302 /* It is else... */
1303 if (cond_depth == cond_min_depth) {
1304 Parse_Error(level, "if-less else");
1305 return COND_INVALID;
1306 }
1307
1308 state = cond_state[cond_depth];
1309 switch (state) {
1310 case SEARCH_FOR_ELIF:
1311 state = ELSE_ACTIVE;
1312 break;
1313 case ELSE_ACTIVE:
1314 case SKIP_TO_ENDIF:
1315 Parse_Error(PARSE_WARNING, "extra else");
1316 /* FALLTHROUGH */
1317 default:
1318 case IF_ACTIVE:
1319 case SKIP_TO_ELSE:
1320 state = SKIP_TO_ENDIF;
1321 break;
1322 }
1323 cond_state[cond_depth] = state;
1324 return state <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP;
1325 }
1326 /* Assume for now it is an elif */
1327 isElif = TRUE;
1328 } else
1329 isElif = FALSE;
1330
1331 if (line[0] != 'i' || line[1] != 'f')
1332 /* Not an ifxxx or elifxxx line */
1333 return COND_INVALID;
1334
1335 /*
1336 * Figure out what sort of conditional it is -- what its default
1337 * function is, etc. -- by looking in the table of valid "ifs"
1338 */
1339 line += 2;
1340 for (ifp = ifs; ; ifp++) {
1341 if (ifp->form == NULL)
1342 return COND_INVALID;
1343 if (istoken(ifp->form, line, ifp->formlen)) {
1344 line += ifp->formlen;
1345 break;
1346 }
1347 }
1348
1349 /* Now we know what sort of 'if' it is... */
1350 state = cond_state[cond_depth];
1351
1352 if (isElif) {
1353 if (cond_depth == cond_min_depth) {
1354 Parse_Error(level, "if-less elif");
1355 return COND_INVALID;
1356 }
1357 if (state == SKIP_TO_ENDIF || state == ELSE_ACTIVE)
1358 Parse_Error(PARSE_WARNING, "extra elif");
1359 if (state != SEARCH_FOR_ELIF) {
1360 /* Either just finished the 'true' block, or already SKIP_TO_ELSE */
1361 cond_state[cond_depth] = SKIP_TO_ELSE;
1362 return COND_SKIP;
1363 }
1364 } else {
1365 if (cond_depth >= MAXIF) {
1366 Parse_Error(PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
1367 return COND_INVALID;
1368 }
1369 cond_depth++;
1370 if (state > ELSE_ACTIVE) {
1371 /* If we aren't parsing the data, treat as always false */
1372 cond_state[cond_depth] = SKIP_TO_ELSE;
1373 return COND_SKIP;
1374 }
1375 }
1376
1377 /* Initialize file-global variables for parsing the expression */
1378 condDefProc = ifp->defProc;
1379 condInvert = ifp->doNot;
1380
1381 /* And evaluate the conditional expresssion */
1382 if (Cond_EvalExpression(0, line, &value, 1) == COND_INVALID) {
1383 /* Although we get make to reprocess the line, set a state */
1384 cond_state[cond_depth] = SEARCH_FOR_ELIF;
1385 return COND_INVALID;
1386 }
1387
1388 if (!value) {
1389 cond_state[cond_depth] = SEARCH_FOR_ELIF;
1390 return COND_SKIP;
1391 }
1392 cond_state[cond_depth] = IF_ACTIVE;
1393 return COND_PARSE;
1394 }
1395
1396
1397
1398 /*-
1400 *-----------------------------------------------------------------------
1401 * Cond_End --
1402 * Make sure everything's clean at the end of a makefile.
1403 *
1404 * Results:
1405 * None.
1406 *
1407 * Side Effects:
1408 * Parse_Error will be called if open conditionals are around.
1409 *
1410 *-----------------------------------------------------------------------
1411 */
1412 void
1413 Cond_restore_depth(unsigned int saved_depth)
1414 {
1415 int open_conds = cond_depth - cond_min_depth;
1416
1417 if (open_conds != 0 || saved_depth > cond_depth) {
1418 Parse_Error(PARSE_FATAL, "%d open conditional%s", open_conds,
1419 open_conds == 1 ? "" : "s");
1420 cond_depth = cond_min_depth;
1421 }
1422
1423 cond_min_depth = saved_depth;
1424 }
1425
1426 unsigned int
1427 Cond_save_depth(void)
1428 {
1429 int depth = cond_min_depth;
1430
1431 cond_min_depth = cond_depth;
1432 return depth;
1433 }
1434