cond.c revision 1.168 1 /* $NetBSD: cond.c,v 1.168 2020/10/24 04:51:19 rillig 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 /* Handling of conditionals in a makefile.
73 *
74 * Interface:
75 * Cond_EvalLine Evaluate the conditional.
76 *
77 * Cond_EvalCondition
78 * Evaluate the conditional, which is either the argument
79 * of one of the .if directives or the condition in a
80 * ':?then:else' variable modifier.
81 *
82 * Cond_save_depth
83 * Cond_restore_depth
84 * Save and restore the nesting of the conditions, at
85 * the start and end of including another makefile, to
86 * ensure that in each makefile the conditional
87 * directives are well-balanced.
88 */
89
90 #include <errno.h>
91
92 #include "make.h"
93 #include "dir.h"
94
95 /* "@(#)cond.c 8.2 (Berkeley) 1/2/94" */
96 MAKE_RCSID("$NetBSD: cond.c,v 1.168 2020/10/24 04:51:19 rillig Exp $");
97
98 /*
99 * The parsing of conditional expressions is based on this grammar:
100 * E -> F || E
101 * E -> F
102 * F -> T && F
103 * F -> T
104 * T -> defined(variable)
105 * T -> make(target)
106 * T -> exists(file)
107 * T -> empty(varspec)
108 * T -> target(name)
109 * T -> commands(name)
110 * T -> symbol
111 * T -> $(varspec) op value
112 * T -> $(varspec) == "string"
113 * T -> $(varspec) != "string"
114 * T -> "string"
115 * T -> ( E )
116 * T -> ! T
117 * op -> == | != | > | < | >= | <=
118 *
119 * 'symbol' is some other symbol to which the default function is applied.
120 *
121 * The tokens are scanned by CondToken, which returns:
122 * TOK_AND for '&' or '&&'
123 * TOK_OR for '|' or '||'
124 * TOK_NOT for '!'
125 * TOK_LPAREN for '('
126 * TOK_RPAREN for ')'
127 * Other terminal symbols are evaluated using either the default function or
128 * the function given in the terminal, they return either TOK_TRUE or
129 * TOK_FALSE.
130 *
131 * TOK_FALSE is 0 and TOK_TRUE 1 so we can directly assign C comparisons.
132 *
133 * All non-terminal functions (CondParser_Expr, CondParser_Factor and
134 * CondParser_Term) return either TOK_FALSE, TOK_TRUE, or TOK_ERROR on error.
135 */
136 typedef enum Token {
137 TOK_FALSE = 0, TOK_TRUE = 1, TOK_AND, TOK_OR, TOK_NOT,
138 TOK_LPAREN, TOK_RPAREN, TOK_EOF, TOK_NONE, TOK_ERROR
139 } Token;
140
141 typedef struct CondParser {
142 const struct If *if_info; /* Info for current statement */
143 const char *p; /* The remaining condition to parse */
144 Token curr; /* Single push-back token used in parsing */
145
146 /* Whether an error message has already been printed for this condition.
147 * The first available error message is usually the most specific one,
148 * therefore it makes sense to suppress the standard "Malformed
149 * conditional" message. */
150 Boolean printedError;
151 } CondParser;
152
153 static Token CondParser_Expr(CondParser *par, Boolean);
154
155 static unsigned int cond_depth = 0; /* current .if nesting level */
156 static unsigned int cond_min_depth = 0; /* depth at makefile open */
157
158 /*
159 * Indicate when we should be strict about lhs of comparisons.
160 * In strict mode, the lhs must be a variable expression or a string literal
161 * in quotes. In non-strict mode it may also be an unquoted string literal.
162 *
163 * TRUE when CondEvalExpression is called from Cond_EvalLine (.if etc)
164 * FALSE when CondEvalExpression is called from ApplyModifier_IfElse
165 * since lhs is already expanded and we cannot tell if
166 * it was a variable reference or not.
167 */
168 static Boolean lhsStrict;
169
170 static int
171 is_token(const char *str, const char *tok, size_t len)
172 {
173 return strncmp(str, tok, len) == 0 && !ch_isalpha(str[len]);
174 }
175
176 /* Push back the most recent token read. We only need one level of this. */
177 static void
178 CondParser_PushBack(CondParser *par, Token t)
179 {
180 assert(par->curr == TOK_NONE);
181 assert(t != TOK_NONE);
182
183 par->curr = t;
184 }
185
186 static void
187 CondParser_SkipWhitespace(CondParser *par)
188 {
189 cpp_skip_whitespace(&par->p);
190 }
191
192 /* Parse the argument of a built-in function.
193 *
194 * Arguments:
195 * *pp initially points at the '(',
196 * upon successful return it points right after the ')'.
197 *
198 * *out_arg receives the argument as string.
199 *
200 * func says whether the argument belongs to an actual function, or
201 * whether the parsed argument is passed to the default function.
202 *
203 * Return the length of the argument. */
204 static size_t
205 ParseFuncArg(const char **pp, Boolean doEval, const char *func,
206 char **out_arg) {
207 const char *p = *pp;
208 Buffer argBuf;
209 int paren_depth;
210 size_t argLen;
211
212 if (func != NULL)
213 p++; /* Skip opening '(' - verified by caller */
214
215 if (*p == '\0') {
216 /*
217 * No arguments whatsoever. Because 'make' and 'defined' aren't really
218 * "reserved words", we don't print a message. I think this is better
219 * than hitting the user with a warning message every time s/he uses
220 * the word 'make' or 'defined' at the beginning of a symbol...
221 */
222 *out_arg = NULL;
223 return 0;
224 }
225
226 while (*p == ' ' || *p == '\t') {
227 p++;
228 }
229
230 Buf_Init(&argBuf, 16);
231
232 paren_depth = 0;
233 for (;;) {
234 char ch = *p;
235 if (ch == 0 || ch == ' ' || ch == '\t')
236 break;
237 if ((ch == '&' || ch == '|') && paren_depth == 0)
238 break;
239 if (*p == '$') {
240 /*
241 * Parse the variable spec and install it as part of the argument
242 * if it's valid. We tell Var_Parse to complain on an undefined
243 * variable, so we don't need to do it. Nor do we return an error,
244 * though perhaps we should...
245 */
246 void *nestedVal_freeIt;
247 VarEvalFlags eflags = VARE_UNDEFERR | (doEval ? VARE_WANTRES : 0);
248 const char *nestedVal;
249 (void)Var_Parse(&p, VAR_CMD, eflags, &nestedVal, &nestedVal_freeIt);
250 /* TODO: handle errors */
251 Buf_AddStr(&argBuf, nestedVal);
252 free(nestedVal_freeIt);
253 continue;
254 }
255 if (ch == '(')
256 paren_depth++;
257 else if (ch == ')' && --paren_depth < 0)
258 break;
259 Buf_AddByte(&argBuf, *p);
260 p++;
261 }
262
263 *out_arg = Buf_GetAll(&argBuf, &argLen);
264 Buf_Destroy(&argBuf, FALSE);
265
266 while (*p == ' ' || *p == '\t') {
267 p++;
268 }
269
270 if (func != NULL && *p++ != ')') {
271 Parse_Error(PARSE_WARNING, "Missing closing parenthesis for %s()",
272 func);
273 /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
274 return 0;
275 }
276
277 *pp = p;
278 return argLen;
279 }
280
281 /* Test whether the given variable is defined. */
282 static Boolean
283 FuncDefined(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
284 {
285 char *freeIt;
286 Boolean result = Var_Value(arg, VAR_CMD, &freeIt) != NULL;
287 bmake_free(freeIt);
288 return result;
289 }
290
291 /* See if the given target is being made. */
292 static Boolean
293 FuncMake(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
294 {
295 StringListNode *ln;
296
297 for (ln = create->first; ln != NULL; ln = ln->next)
298 if (Str_Match(ln->datum, arg))
299 return TRUE;
300 return FALSE;
301 }
302
303 /* See if the given file exists. */
304 static Boolean
305 FuncExists(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
306 {
307 Boolean result;
308 char *path;
309
310 path = Dir_FindFile(arg, dirSearchPath);
311 DEBUG2(COND, "exists(%s) result is \"%s\"\n", arg, path ? path : "");
312 if (path != NULL) {
313 result = TRUE;
314 free(path);
315 } else {
316 result = FALSE;
317 }
318 return result;
319 }
320
321 /* See if the given node exists and is an actual target. */
322 static Boolean
323 FuncTarget(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
324 {
325 GNode *gn = Targ_FindNode(arg);
326 return gn != NULL && GNode_IsTarget(gn);
327 }
328
329 /* See if the given node exists and is an actual target with commands
330 * associated with it. */
331 static Boolean
332 FuncCommands(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
333 {
334 GNode *gn = Targ_FindNode(arg);
335 return gn != NULL && GNode_IsTarget(gn) && !Lst_IsEmpty(gn->commands);
336 }
337
338 /*-
339 * Convert the given number into a double.
340 * We try a base 10 or 16 integer conversion first, if that fails
341 * then we try a floating point conversion instead.
342 *
343 * Results:
344 * Sets 'value' to double value of string.
345 * Returns TRUE if the conversion succeeded.
346 */
347 static Boolean
348 TryParseNumber(const char *str, double *value)
349 {
350 char *eptr, ech;
351 unsigned long l_val;
352 double d_val;
353
354 errno = 0;
355 if (!*str) {
356 *value = 0.0;
357 return TRUE;
358 }
359 l_val = strtoul(str, &eptr, str[1] == 'x' ? 16 : 10);
360 ech = *eptr;
361 if (ech == '\0' && errno != ERANGE) {
362 d_val = str[0] == '-' ? -(double)-l_val : (double)l_val;
363 } else {
364 if (ech != '\0' && ech != '.' && ech != 'e' && ech != 'E')
365 return FALSE;
366 d_val = strtod(str, &eptr);
367 if (*eptr)
368 return FALSE;
369 }
370
371 *value = d_val;
372 return TRUE;
373 }
374
375 static Boolean
376 is_separator(char ch)
377 {
378 return ch == '\0' || ch_isspace(ch) || strchr("!=><)", ch);
379 }
380
381 /*-
382 * Parse a string from a variable reference or an optionally quoted
383 * string. This is called for the lhs and rhs of string comparisons.
384 *
385 * Results:
386 * Returns the string, absent any quotes, or NULL on error.
387 * Sets quoted if the string was quoted.
388 * Sets freeIt if needed.
389 */
390 /* coverity:[+alloc : arg-*4] */
391 static const char *
392 CondParser_String(CondParser *par, Boolean doEval, Boolean strictLHS,
393 Boolean *quoted, void **freeIt)
394 {
395 Buffer buf;
396 const char *str;
397 Boolean atStart;
398 const char *nested_p;
399 Boolean qt;
400 const char *start;
401 VarEvalFlags eflags;
402 VarParseResult parseResult;
403
404 Buf_Init(&buf, 0);
405 str = NULL;
406 *freeIt = NULL;
407 *quoted = qt = par->p[0] == '"' ? 1 : 0;
408 if (qt)
409 par->p++;
410 start = par->p;
411 while (par->p[0] && str == NULL) {
412 switch (par->p[0]) {
413 case '\\':
414 par->p++;
415 if (par->p[0] != '\0') {
416 Buf_AddByte(&buf, par->p[0]);
417 par->p++;
418 }
419 continue;
420 case '"':
421 if (qt) {
422 par->p++; /* we don't want the quotes */
423 goto got_str;
424 }
425 Buf_AddByte(&buf, par->p[0]); /* likely? */
426 par->p++;
427 continue;
428 case ')':
429 case '!':
430 case '=':
431 case '>':
432 case '<':
433 case ' ':
434 case '\t':
435 if (!qt)
436 goto got_str;
437 Buf_AddByte(&buf, par->p[0]);
438 par->p++;
439 continue;
440 case '$':
441 /* if we are in quotes, an undefined variable is ok */
442 eflags = ((!qt && doEval) ? VARE_UNDEFERR : 0) |
443 (doEval ? VARE_WANTRES : 0);
444 nested_p = par->p;
445 atStart = nested_p == start;
446 parseResult = Var_Parse(&nested_p, VAR_CMD, eflags, &str, freeIt);
447 /* TODO: handle errors */
448 if (str == var_Error) {
449 if (parseResult & VPR_ANY_MSG)
450 par->printedError = TRUE;
451 if (*freeIt) {
452 free(*freeIt);
453 *freeIt = NULL;
454 }
455 /*
456 * Even if !doEval, we still report syntax errors, which
457 * is what getting var_Error back with !doEval means.
458 */
459 str = NULL;
460 goto cleanup;
461 }
462 par->p = nested_p;
463
464 /*
465 * If the '$' started the string literal (which means no quotes),
466 * and the variable expression is followed by a space, looks like
467 * a comparison operator or is the end of the expression, we are
468 * done.
469 */
470 if (atStart && is_separator(par->p[0]))
471 goto cleanup;
472
473 Buf_AddStr(&buf, str);
474 if (*freeIt) {
475 free(*freeIt);
476 *freeIt = NULL;
477 }
478 str = NULL; /* not finished yet */
479 continue;
480 default:
481 if (strictLHS && !qt && *start != '$' && !ch_isdigit(*start)) {
482 /* lhs must be quoted, a variable reference or number */
483 if (*freeIt) {
484 free(*freeIt);
485 *freeIt = NULL;
486 }
487 str = NULL;
488 goto cleanup;
489 }
490 Buf_AddByte(&buf, par->p[0]);
491 par->p++;
492 continue;
493 }
494 }
495 got_str:
496 *freeIt = Buf_GetAll(&buf, NULL);
497 str = *freeIt;
498 cleanup:
499 Buf_Destroy(&buf, FALSE);
500 return str;
501 }
502
503 /* The different forms of .if directives. */
504 static const struct If {
505 const char *form; /* Form of if */
506 size_t formlen; /* Length of form */
507 Boolean doNot; /* TRUE if default function should be negated */
508 Boolean (*defProc)(size_t, const char *); /* Default function to apply */
509 } ifs[] = {
510 { "def", 3, FALSE, FuncDefined },
511 { "ndef", 4, TRUE, FuncDefined },
512 { "make", 4, FALSE, FuncMake },
513 { "nmake", 5, TRUE, FuncMake },
514 { "", 0, FALSE, FuncDefined },
515 { NULL, 0, FALSE, NULL }
516 };
517
518 /* Evaluate a "comparison without operator", such as in ".if ${VAR}" or
519 * ".if 0". */
520 static Token
521 EvalNotEmpty(CondParser *par, const char *lhs, Boolean lhsQuoted)
522 {
523 double left;
524
525 /* For .ifxxx "..." check for non-empty string. */
526 if (lhsQuoted)
527 return lhs[0] != '\0';
528
529 /* For .ifxxx <number> compare against zero */
530 if (TryParseNumber(lhs, &left))
531 return left != 0.0;
532
533 /* For .if ${...} check for non-empty string (defProc is ifdef). */
534 if (par->if_info->form[0] == '\0')
535 return lhs[0] != 0;
536
537 /* Otherwise action default test ... */
538 return par->if_info->defProc(strlen(lhs), lhs) == !par->if_info->doNot;
539 }
540
541 /* Evaluate a numerical comparison, such as in ".if ${VAR} >= 9". */
542 static Token
543 EvalCompareNum(double lhs, const char *op, double rhs)
544 {
545 DEBUG3(COND, "lhs = %f, rhs = %f, op = %.2s\n", lhs, rhs, op);
546
547 switch (op[0]) {
548 case '!':
549 if (op[1] != '=') {
550 Parse_Error(PARSE_WARNING, "Unknown operator");
551 /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
552 return TOK_ERROR;
553 }
554 return lhs != rhs;
555 case '=':
556 if (op[1] != '=') {
557 Parse_Error(PARSE_WARNING, "Unknown operator");
558 /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
559 return TOK_ERROR;
560 }
561 return lhs == rhs;
562 case '<':
563 return op[1] == '=' ? lhs <= rhs : lhs < rhs;
564 case '>':
565 return op[1] == '=' ? lhs >= rhs : lhs > rhs;
566 }
567 return TOK_ERROR;
568 }
569
570 static Token
571 EvalCompareStr(const char *lhs, const char *op, const char *rhs)
572 {
573 if (!((op[0] == '!' || op[0] == '=') && op[1] == '=')) {
574 Parse_Error(PARSE_WARNING,
575 "String comparison operator must be either == or !=");
576 /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
577 return TOK_ERROR;
578 }
579
580 DEBUG3(COND, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n", lhs, rhs, op);
581 return (*op == '=') == (strcmp(lhs, rhs) == 0);
582 }
583
584 /* Evaluate a comparison, such as "${VAR} == 12345". */
585 static Token
586 EvalCompare(const char *lhs, Boolean lhsQuoted, const char *op,
587 const char *rhs, Boolean rhsQuoted)
588 {
589 double left, right;
590
591 if (!rhsQuoted && !lhsQuoted)
592 if (TryParseNumber(lhs, &left) && TryParseNumber(rhs, &right))
593 return EvalCompareNum(left, op, right);
594
595 return EvalCompareStr(lhs, op, rhs);
596 }
597
598 /* Parse a comparison condition such as:
599 *
600 * 0
601 * ${VAR:Mpattern}
602 * ${VAR} == value
603 * ${VAR:U0} < 12345
604 */
605 static Token
606 CondParser_Comparison(CondParser *par, Boolean doEval)
607 {
608 Token t = TOK_ERROR;
609 const char *lhs, *op, *rhs;
610 void *lhsFree, *rhsFree;
611 Boolean lhsQuoted, rhsQuoted;
612
613 rhs = NULL;
614 lhsFree = rhsFree = NULL;
615 lhsQuoted = rhsQuoted = FALSE;
616
617 /*
618 * Parse the variable spec and skip over it, saving its
619 * value in lhs.
620 */
621 lhs = CondParser_String(par, doEval, lhsStrict, &lhsQuoted, &lhsFree);
622 if (!lhs)
623 goto done;
624
625 CondParser_SkipWhitespace(par);
626
627 /*
628 * Make sure the operator is a valid one. If it isn't a
629 * known relational operator, pretend we got a
630 * != 0 comparison.
631 */
632 op = par->p;
633 switch (par->p[0]) {
634 case '!':
635 case '=':
636 case '<':
637 case '>':
638 if (par->p[1] == '=') {
639 par->p += 2;
640 } else {
641 par->p++;
642 }
643 break;
644 default:
645 t = doEval ? EvalNotEmpty(par, lhs, lhsQuoted) : TOK_FALSE;
646 goto done;
647 }
648
649 CondParser_SkipWhitespace(par);
650
651 if (par->p[0] == '\0') {
652 Parse_Error(PARSE_WARNING, "Missing right-hand-side of operator");
653 /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
654 goto done;
655 }
656
657 rhs = CondParser_String(par, doEval, FALSE, &rhsQuoted, &rhsFree);
658 if (rhs == NULL)
659 goto done;
660
661 if (!doEval) {
662 t = TOK_FALSE;
663 goto done;
664 }
665
666 t = EvalCompare(lhs, lhsQuoted, op, rhs, rhsQuoted);
667
668 done:
669 free(lhsFree);
670 free(rhsFree);
671 return t;
672 }
673
674 static size_t
675 ParseEmptyArg(const char **linePtr, Boolean doEval,
676 const char *func MAKE_ATTR_UNUSED, char **argPtr)
677 {
678 void *val_freeIt;
679 const char *val;
680 size_t magic_res;
681
682 /* We do all the work here and return the result as the length */
683 *argPtr = NULL;
684
685 (*linePtr)--; /* Make (*linePtr)[1] point to the '('. */
686 (void)Var_Parse(linePtr, VAR_CMD, doEval ? VARE_WANTRES : 0,
687 &val, &val_freeIt);
688 /* TODO: handle errors */
689 /* If successful, *linePtr points beyond the closing ')' now. */
690
691 if (val == var_Error) {
692 free(val_freeIt);
693 return (size_t)-1;
694 }
695
696 /* A variable is empty when it just contains spaces... 4/15/92, christos */
697 cpp_skip_whitespace(&val);
698
699 /*
700 * For consistency with the other functions we can't generate the
701 * true/false here.
702 */
703 magic_res = *val != '\0' ? 2 : 1;
704 free(val_freeIt);
705 return magic_res;
706 }
707
708 static Boolean
709 FuncEmpty(size_t arglen, const char *arg MAKE_ATTR_UNUSED)
710 {
711 /* Magic values ahead, see ParseEmptyArg. */
712 return arglen == 1;
713 }
714
715 static Token
716 CondParser_Func(CondParser *par, Boolean doEval)
717 {
718 static const struct fn_def {
719 const char *fn_name;
720 size_t fn_name_len;
721 size_t (*fn_parse)(const char **, Boolean, const char *, char **);
722 Boolean (*fn_eval)(size_t, const char *);
723 } fn_defs[] = {
724 { "defined", 7, ParseFuncArg, FuncDefined },
725 { "make", 4, ParseFuncArg, FuncMake },
726 { "exists", 6, ParseFuncArg, FuncExists },
727 { "empty", 5, ParseEmptyArg, FuncEmpty },
728 { "target", 6, ParseFuncArg, FuncTarget },
729 { "commands", 8, ParseFuncArg, FuncCommands },
730 { NULL, 0, NULL, NULL },
731 };
732 const struct fn_def *fn_def;
733 Token t;
734 char *arg = NULL;
735 size_t arglen;
736 const char *cp = par->p;
737 const char *cp1;
738
739 for (fn_def = fn_defs; fn_def->fn_name != NULL; fn_def++) {
740 if (!is_token(cp, fn_def->fn_name, fn_def->fn_name_len))
741 continue;
742 cp += fn_def->fn_name_len;
743 /* There can only be whitespace before the '(' */
744 cpp_skip_whitespace(&cp);
745 if (*cp != '(')
746 break;
747
748 arglen = fn_def->fn_parse(&cp, doEval, fn_def->fn_name, &arg);
749 if (arglen == 0 || arglen == (size_t)-1) {
750 par->p = cp;
751 return arglen == 0 ? TOK_FALSE : TOK_ERROR;
752 }
753 /* Evaluate the argument using the required function. */
754 t = !doEval || fn_def->fn_eval(arglen, arg);
755 free(arg);
756 par->p = cp;
757 return t;
758 }
759
760 /* Push anything numeric through the compare expression */
761 cp = par->p;
762 if (ch_isdigit(cp[0]) || strchr("+-", cp[0]))
763 return CondParser_Comparison(par, doEval);
764
765 /*
766 * Most likely we have a naked token to apply the default function to.
767 * However ".if a == b" gets here when the "a" is unquoted and doesn't
768 * start with a '$'. This surprises people.
769 * If what follows the function argument is a '=' or '!' then the syntax
770 * would be invalid if we did "defined(a)" - so instead treat as an
771 * expression.
772 */
773 arglen = ParseFuncArg(&cp, doEval, NULL, &arg);
774 cp1 = cp;
775 cpp_skip_whitespace(&cp1);
776 if (*cp1 == '=' || *cp1 == '!')
777 return CondParser_Comparison(par, doEval);
778 par->p = cp;
779
780 /*
781 * Evaluate the argument using the default function.
782 * This path always treats .if as .ifdef. To get here, the character
783 * after .if must have been taken literally, so the argument cannot
784 * be empty - even if it contained a variable expansion.
785 */
786 t = !doEval || par->if_info->defProc(arglen, arg) == !par->if_info->doNot;
787 free(arg);
788 return t;
789 }
790
791 /* Return the next token or comparison result from the parser. */
792 static Token
793 CondParser_Token(CondParser *par, Boolean doEval)
794 {
795 Token t;
796
797 t = par->curr;
798 if (t != TOK_NONE) {
799 par->curr = TOK_NONE;
800 return t;
801 }
802
803 while (par->p[0] == ' ' || par->p[0] == '\t') {
804 par->p++;
805 }
806
807 switch (par->p[0]) {
808
809 case '(':
810 par->p++;
811 return TOK_LPAREN;
812
813 case ')':
814 par->p++;
815 return TOK_RPAREN;
816
817 case '|':
818 par->p++;
819 if (par->p[0] == '|') {
820 par->p++;
821 }
822 return TOK_OR;
823
824 case '&':
825 par->p++;
826 if (par->p[0] == '&') {
827 par->p++;
828 }
829 return TOK_AND;
830
831 case '!':
832 par->p++;
833 return TOK_NOT;
834
835 case '#':
836 case '\n':
837 case '\0':
838 return TOK_EOF;
839
840 case '"':
841 case '$':
842 return CondParser_Comparison(par, doEval);
843
844 default:
845 return CondParser_Func(par, doEval);
846 }
847 }
848
849 /* Parse a single term in the expression. This consists of a terminal symbol
850 * or TOK_NOT and a term (not including the binary operators):
851 *
852 * T -> defined(variable) | make(target) | exists(file) | symbol
853 * T -> ! T | ( E )
854 *
855 * Results:
856 * TOK_TRUE, TOK_FALSE or TOK_ERROR.
857 */
858 static Token
859 CondParser_Term(CondParser *par, Boolean doEval)
860 {
861 Token t;
862
863 t = CondParser_Token(par, doEval);
864
865 if (t == TOK_EOF) {
866 /*
867 * If we reached the end of the expression, the expression
868 * is malformed...
869 */
870 t = TOK_ERROR;
871 } else if (t == TOK_LPAREN) {
872 /*
873 * T -> ( E )
874 */
875 t = CondParser_Expr(par, doEval);
876 if (t != TOK_ERROR) {
877 if (CondParser_Token(par, doEval) != TOK_RPAREN) {
878 t = TOK_ERROR;
879 }
880 }
881 } else if (t == TOK_NOT) {
882 t = CondParser_Term(par, doEval);
883 if (t == TOK_TRUE) {
884 t = TOK_FALSE;
885 } else if (t == TOK_FALSE) {
886 t = TOK_TRUE;
887 }
888 }
889 return t;
890 }
891
892 /* Parse a conjunctive factor (nice name, wot?)
893 *
894 * F -> T && F | T
895 *
896 * Results:
897 * TOK_TRUE, TOK_FALSE or TOK_ERROR
898 */
899 static Token
900 CondParser_Factor(CondParser *par, Boolean doEval)
901 {
902 Token l, o;
903
904 l = CondParser_Term(par, doEval);
905 if (l != TOK_ERROR) {
906 o = CondParser_Token(par, doEval);
907
908 if (o == TOK_AND) {
909 /*
910 * F -> T && F
911 *
912 * If T is TOK_FALSE, the whole thing will be TOK_FALSE, but we
913 * have to parse the r.h.s. anyway (to throw it away).
914 * If T is TOK_TRUE, the result is the r.h.s., be it a TOK_ERROR
915 * or not.
916 */
917 if (l == TOK_TRUE) {
918 l = CondParser_Factor(par, doEval);
919 } else {
920 (void)CondParser_Factor(par, FALSE);
921 }
922 } else {
923 /*
924 * F -> T
925 */
926 CondParser_PushBack(par, o);
927 }
928 }
929 return l;
930 }
931
932 /* Main expression production.
933 *
934 * E -> F || E | F
935 *
936 * Results:
937 * TOK_TRUE, TOK_FALSE or TOK_ERROR.
938 */
939 static Token
940 CondParser_Expr(CondParser *par, Boolean doEval)
941 {
942 Token l, o;
943
944 l = CondParser_Factor(par, doEval);
945 if (l != TOK_ERROR) {
946 o = CondParser_Token(par, doEval);
947
948 if (o == TOK_OR) {
949 /*
950 * E -> F || E
951 *
952 * A similar thing occurs for ||, except that here we make sure
953 * the l.h.s. is TOK_FALSE before we bother to evaluate the r.h.s.
954 * Once again, if l is TOK_FALSE, the result is the r.h.s. and once
955 * again if l is TOK_TRUE, we parse the r.h.s. to throw it away.
956 */
957 if (l == TOK_FALSE) {
958 l = CondParser_Expr(par, doEval);
959 } else {
960 (void)CondParser_Expr(par, FALSE);
961 }
962 } else {
963 /*
964 * E -> F
965 */
966 CondParser_PushBack(par, o);
967 }
968 }
969 return l;
970 }
971
972 static CondEvalResult
973 CondParser_Eval(CondParser *par, Boolean *value)
974 {
975 Token res;
976
977 DEBUG1(COND, "CondParser_Eval: %s\n", par->p);
978
979 res = CondParser_Expr(par, TRUE);
980 if (res != TOK_FALSE && res != TOK_TRUE)
981 return COND_INVALID;
982
983 if (CondParser_Token(par, TRUE /* XXX: Why TRUE? */) != TOK_EOF)
984 return COND_INVALID;
985
986 *value = res == TOK_TRUE;
987 return COND_PARSE;
988 }
989
990 /* Evaluate the condition, including any side effects from the variable
991 * expressions in the condition. The condition consists of &&, ||, !,
992 * function(arg), comparisons and parenthetical groupings thereof.
993 *
994 * Results:
995 * COND_PARSE if the condition was valid grammatically
996 * COND_INVALID if not a valid conditional.
997 *
998 * (*value) is set to the boolean value of the condition
999 */
1000 static CondEvalResult
1001 CondEvalExpression(const struct If *info, const char *cond, Boolean *value,
1002 Boolean eprint, Boolean strictLHS)
1003 {
1004 static const struct If *dflt_info;
1005 CondParser par;
1006 int rval;
1007
1008 lhsStrict = strictLHS;
1009
1010 while (*cond == ' ' || *cond == '\t')
1011 cond++;
1012
1013 if (info == NULL && (info = dflt_info) == NULL) {
1014 /* Scan for the entry for .if - it can't be first */
1015 for (info = ifs;; info++)
1016 if (info->form[0] == 0)
1017 break;
1018 dflt_info = info;
1019 }
1020 assert(info != NULL);
1021
1022 par.if_info = info;
1023 par.p = cond;
1024 par.curr = TOK_NONE;
1025 par.printedError = FALSE;
1026
1027 rval = CondParser_Eval(&par, value);
1028
1029 if (rval == COND_INVALID && eprint && !par.printedError)
1030 Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", cond);
1031
1032 return rval;
1033 }
1034
1035 CondEvalResult
1036 Cond_EvalCondition(const char *cond, Boolean *out_value)
1037 {
1038 return CondEvalExpression(NULL, cond, out_value, FALSE, FALSE);
1039 }
1040
1041 /* Evaluate the conditional in the passed line. The line looks like this:
1042 * .<cond-type> <expr>
1043 * In this line, <cond-type> is any of if, ifmake, ifnmake, ifdef, ifndef,
1044 * elif, elifmake, elifnmake, elifdef, elifndef.
1045 * In this line, <expr> consists of &&, ||, !, function(arg), comparisons
1046 * and parenthetical groupings thereof.
1047 *
1048 * Note that the states IF_ACTIVE and ELSE_ACTIVE are only different in order
1049 * to detect spurious .else lines (as are SKIP_TO_ELSE and SKIP_TO_ENDIF),
1050 * otherwise .else could be treated as '.elif 1'.
1051 *
1052 * Results:
1053 * COND_PARSE to continue parsing the lines after the conditional
1054 * (when .if or .else returns TRUE)
1055 * COND_SKIP to skip the lines after the conditional
1056 * (when .if or .elif returns FALSE, or when a previous
1057 * branch has already been taken)
1058 * COND_INVALID if the conditional was not valid, either because of
1059 * a syntax error or because some variable was undefined
1060 * or because the condition could not be evaluated
1061 */
1062 CondEvalResult
1063 Cond_EvalLine(const char *line)
1064 {
1065 enum { MAXIF = 128 }; /* maximum depth of .if'ing */
1066 enum { MAXIF_BUMP = 32 }; /* how much to grow by */
1067 enum if_states {
1068 IF_ACTIVE, /* .if or .elif part active */
1069 ELSE_ACTIVE, /* .else part active */
1070 SEARCH_FOR_ELIF, /* searching for .elif/else to execute */
1071 SKIP_TO_ELSE, /* has been true, but not seen '.else' */
1072 SKIP_TO_ENDIF /* nothing else to execute */
1073 };
1074 static enum if_states *cond_state = NULL;
1075 static unsigned int max_if_depth = MAXIF;
1076
1077 const struct If *ifp;
1078 Boolean isElif;
1079 Boolean value;
1080 enum if_states state;
1081
1082 if (!cond_state) {
1083 cond_state = bmake_malloc(max_if_depth * sizeof(*cond_state));
1084 cond_state[0] = IF_ACTIVE;
1085 }
1086 /* skip leading character (the '.') and any whitespace */
1087 for (line++; *line == ' ' || *line == '\t'; line++)
1088 continue;
1089
1090 /* Find what type of if we're dealing with. */
1091 if (line[0] == 'e') {
1092 if (line[1] != 'l') {
1093 if (!is_token(line + 1, "ndif", 4))
1094 return COND_INVALID;
1095 /* End of conditional section */
1096 if (cond_depth == cond_min_depth) {
1097 Parse_Error(PARSE_FATAL, "if-less endif");
1098 return COND_PARSE;
1099 }
1100 /* Return state for previous conditional */
1101 cond_depth--;
1102 return cond_state[cond_depth] <= ELSE_ACTIVE
1103 ? COND_PARSE : COND_SKIP;
1104 }
1105
1106 /* Quite likely this is 'else' or 'elif' */
1107 line += 2;
1108 if (is_token(line, "se", 2)) {
1109 /* It is else... */
1110 if (cond_depth == cond_min_depth) {
1111 Parse_Error(PARSE_FATAL, "if-less else");
1112 return COND_PARSE;
1113 }
1114
1115 state = cond_state[cond_depth];
1116 switch (state) {
1117 case SEARCH_FOR_ELIF:
1118 state = ELSE_ACTIVE;
1119 break;
1120 case ELSE_ACTIVE:
1121 case SKIP_TO_ENDIF:
1122 Parse_Error(PARSE_WARNING, "extra else");
1123 /* FALLTHROUGH */
1124 default:
1125 case IF_ACTIVE:
1126 case SKIP_TO_ELSE:
1127 state = SKIP_TO_ENDIF;
1128 break;
1129 }
1130 cond_state[cond_depth] = state;
1131 return state <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP;
1132 }
1133 /* Assume for now it is an elif */
1134 isElif = TRUE;
1135 } else
1136 isElif = FALSE;
1137
1138 if (line[0] != 'i' || line[1] != 'f')
1139 /* Not an ifxxx or elifxxx line */
1140 return COND_INVALID;
1141
1142 /*
1143 * Figure out what sort of conditional it is -- what its default
1144 * function is, etc. -- by looking in the table of valid "ifs"
1145 */
1146 line += 2;
1147 for (ifp = ifs;; ifp++) {
1148 if (ifp->form == NULL)
1149 return COND_INVALID;
1150 if (is_token(ifp->form, line, ifp->formlen)) {
1151 line += ifp->formlen;
1152 break;
1153 }
1154 }
1155
1156 /* Now we know what sort of 'if' it is... */
1157
1158 if (isElif) {
1159 if (cond_depth == cond_min_depth) {
1160 Parse_Error(PARSE_FATAL, "if-less elif");
1161 return COND_PARSE;
1162 }
1163 state = cond_state[cond_depth];
1164 if (state == SKIP_TO_ENDIF || state == ELSE_ACTIVE) {
1165 Parse_Error(PARSE_WARNING, "extra elif");
1166 cond_state[cond_depth] = SKIP_TO_ENDIF;
1167 return COND_SKIP;
1168 }
1169 if (state != SEARCH_FOR_ELIF) {
1170 /* Either just finished the 'true' block, or already SKIP_TO_ELSE */
1171 cond_state[cond_depth] = SKIP_TO_ELSE;
1172 return COND_SKIP;
1173 }
1174 } else {
1175 /* Normal .if */
1176 if (cond_depth + 1 >= max_if_depth) {
1177 /*
1178 * This is rare, but not impossible.
1179 * In meta mode, dirdeps.mk (only runs at level 0)
1180 * can need more than the default.
1181 */
1182 max_if_depth += MAXIF_BUMP;
1183 cond_state = bmake_realloc(cond_state,
1184 max_if_depth * sizeof(*cond_state));
1185 }
1186 state = cond_state[cond_depth];
1187 cond_depth++;
1188 if (state > ELSE_ACTIVE) {
1189 /* If we aren't parsing the data, treat as always false */
1190 cond_state[cond_depth] = SKIP_TO_ELSE;
1191 return COND_SKIP;
1192 }
1193 }
1194
1195 /* And evaluate the conditional expression */
1196 if (CondEvalExpression(ifp, line, &value, TRUE, TRUE) == COND_INVALID) {
1197 /* Syntax error in conditional, error message already output. */
1198 /* Skip everything to matching .endif */
1199 cond_state[cond_depth] = SKIP_TO_ELSE;
1200 return COND_SKIP;
1201 }
1202
1203 if (!value) {
1204 cond_state[cond_depth] = SEARCH_FOR_ELIF;
1205 return COND_SKIP;
1206 }
1207 cond_state[cond_depth] = IF_ACTIVE;
1208 return COND_PARSE;
1209 }
1210
1211 void
1212 Cond_restore_depth(unsigned int saved_depth)
1213 {
1214 unsigned int open_conds = cond_depth - cond_min_depth;
1215
1216 if (open_conds != 0 || saved_depth > cond_depth) {
1217 Parse_Error(PARSE_FATAL, "%u open conditional%s", open_conds,
1218 open_conds == 1 ? "" : "s");
1219 cond_depth = cond_min_depth;
1220 }
1221
1222 cond_min_depth = saved_depth;
1223 }
1224
1225 unsigned int
1226 Cond_save_depth(void)
1227 {
1228 unsigned int depth = cond_min_depth;
1229
1230 cond_min_depth = cond_depth;
1231 return depth;
1232 }
1233