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