cond.c revision 1.294 1 /* $NetBSD: cond.c,v 1.294 2021/12/11 10:28:59 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 /*
73 * Handling of conditionals in a makefile.
74 *
75 * Interface:
76 * Cond_EvalLine Evaluate the conditional directive, such as
77 * '.if <cond>', '.elifnmake <cond>', '.else', '.endif'.
78 *
79 * Cond_EvalCondition
80 * Evaluate the conditional, which is either the argument
81 * of one of the .if directives or the condition in a
82 * ':?then:else' variable modifier.
83 *
84 * Cond_save_depth
85 * Cond_restore_depth
86 * Save and restore the nesting of the conditions, at
87 * the start and end of including another makefile, to
88 * ensure that in each makefile the conditional
89 * directives are well-balanced.
90 */
91
92 #include <errno.h>
93
94 #include "make.h"
95 #include "dir.h"
96
97 /* "@(#)cond.c 8.2 (Berkeley) 1/2/94" */
98 MAKE_RCSID("$NetBSD: cond.c,v 1.294 2021/12/11 10:28:59 rillig Exp $");
99
100 /*
101 * The parsing of conditional expressions is based on this grammar:
102 * Or -> And ('||' And)*
103 * And -> Term ('&&' Term)*
104 * Term -> Function '(' Argument ')'
105 * Term -> Leaf Operator Leaf
106 * Term -> Leaf
107 * Term -> '(' Or ')'
108 * Term -> '!' Term
109 * Leaf -> "string"
110 * Leaf -> Number
111 * Leaf -> VariableExpression
112 * Leaf -> Symbol
113 * Operator -> '==' | '!=' | '>' | '<' | '>=' | '<='
114 *
115 * 'Symbol' is an unquoted string literal to which the default function is
116 * applied.
117 *
118 * The tokens are scanned by CondToken, which returns:
119 * TOK_AND for '&&'
120 * TOK_OR for '||'
121 * TOK_NOT for '!'
122 * TOK_LPAREN for '('
123 * TOK_RPAREN for ')'
124 *
125 * Other terminal symbols are evaluated using either the default function or
126 * the function given in the terminal, they return either TOK_TRUE or
127 * TOK_FALSE.
128 */
129 typedef enum Token {
130 TOK_FALSE, TOK_TRUE, TOK_AND, TOK_OR, TOK_NOT,
131 TOK_LPAREN, TOK_RPAREN, TOK_EOF, TOK_NONE, TOK_ERROR
132 } Token;
133
134 typedef enum CondResult {
135 CR_FALSE, CR_TRUE, CR_ERROR
136 } CondResult;
137
138 typedef enum ComparisonOp {
139 LT, LE, GT, GE, EQ, NE
140 } ComparisonOp;
141
142 typedef struct CondParser {
143
144 /*
145 * The plain '.if ${VAR}' evaluates to true if the value of the
146 * expression has length > 0. The other '.if' variants delegate
147 * to evalBare instead.
148 */
149 bool plain;
150
151 /* The function to apply on unquoted bare words. */
152 bool (*evalBare)(size_t, const char *);
153 bool negateEvalBare;
154
155 /*
156 * Whether the left-hand side of a comparison may be an unquoted
157 * string. This is allowed for expressions of the form
158 * ${condition:?:}, see ApplyModifier_IfElse. Such a condition is
159 * expanded before it is evaluated, due to ease of implementation.
160 * This means that at the point where the condition is evaluated,
161 * make cannot know anymore whether the left-hand side had originally
162 * been a variable expression or a plain word.
163 *
164 * In all other contexts, the left-hand side must either be a
165 * variable expression, a quoted string or a number.
166 */
167 bool leftUnquotedOK;
168
169 const char *p; /* The remaining condition to parse */
170 Token curr; /* Single push-back token used in parsing */
171
172 /*
173 * Whether an error message has already been printed for this
174 * condition. The first available error message is usually the most
175 * specific one, therefore it makes sense to suppress the standard
176 * "Malformed conditional" message.
177 */
178 bool printedError;
179 } CondParser;
180
181 static CondResult CondParser_Or(CondParser *par, bool);
182
183 static unsigned int cond_depth = 0; /* current .if nesting level */
184 static unsigned int cond_min_depth = 0; /* depth at makefile open */
185
186 /* Names for ComparisonOp. */
187 static const char opname[][3] = { "<", "<=", ">", ">=", "==", "!=" };
188
189 static bool
190 is_token(const char *str, const char *tok, unsigned char len)
191 {
192 return strncmp(str, tok, (size_t)len) == 0 && !ch_isalpha(str[len]);
193 }
194
195 static Token
196 ToToken(bool cond)
197 {
198 return cond ? TOK_TRUE : TOK_FALSE;
199 }
200
201 static void
202 CondParser_SkipWhitespace(CondParser *par)
203 {
204 cpp_skip_whitespace(&par->p);
205 }
206
207 /*
208 * Parse the argument of a built-in function.
209 *
210 * Arguments:
211 * *pp initially points at the '(',
212 * upon successful return it points right after the ')'.
213 *
214 * *out_arg receives the argument as string.
215 *
216 * func says whether the argument belongs to an actual function, or
217 * whether the parsed argument is passed to the default function.
218 *
219 * Return the length of the argument, or 0 on error.
220 */
221 static size_t
222 ParseFuncArg(CondParser *par, const char **pp, bool doEval, const char *func,
223 char **out_arg)
224 {
225 const char *p = *pp;
226 Buffer argBuf;
227 int paren_depth;
228 size_t argLen;
229
230 if (func != NULL)
231 p++; /* Skip opening '(' - verified by caller */
232
233 if (*p == '\0') {
234 *out_arg = NULL; /* Missing closing parenthesis: */
235 return 0; /* .if defined( */
236 }
237
238 cpp_skip_hspace(&p);
239
240 Buf_InitSize(&argBuf, 16);
241
242 paren_depth = 0;
243 for (;;) {
244 char ch = *p;
245 if (ch == '\0' || ch == ' ' || ch == '\t')
246 break;
247 if ((ch == '&' || ch == '|') && paren_depth == 0)
248 break;
249 if (*p == '$') {
250 /*
251 * Parse the variable expression and install it as
252 * part of the argument if it's valid. We tell
253 * Var_Parse to complain on an undefined variable,
254 * (XXX: but Var_Parse ignores that request)
255 * so we don't need to do it. Nor do we return an
256 * error, though perhaps we should.
257 */
258 VarEvalMode emode = doEval
259 ? VARE_UNDEFERR
260 : VARE_PARSE_ONLY;
261 FStr nestedVal;
262 (void)Var_Parse(&p, SCOPE_CMDLINE, emode, &nestedVal);
263 /* TODO: handle errors */
264 Buf_AddStr(&argBuf, nestedVal.str);
265 FStr_Done(&nestedVal);
266 continue;
267 }
268 if (ch == '(')
269 paren_depth++;
270 else if (ch == ')' && --paren_depth < 0)
271 break;
272 Buf_AddByte(&argBuf, *p);
273 p++;
274 }
275
276 argLen = argBuf.len;
277 *out_arg = Buf_DoneData(&argBuf);
278
279 cpp_skip_hspace(&p);
280
281 if (func != NULL && *p++ != ')') {
282 Parse_Error(PARSE_FATAL,
283 "Missing closing parenthesis for %s()", func);
284 par->printedError = true;
285 return 0;
286 }
287
288 *pp = p;
289 return argLen;
290 }
291
292 /* Test whether the given variable is defined. */
293 /*ARGSUSED*/
294 static bool
295 FuncDefined(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
296 {
297 FStr value = Var_Value(SCOPE_CMDLINE, arg);
298 bool result = value.str != NULL;
299 FStr_Done(&value);
300 return result;
301 }
302
303 /* See if the given target is requested to be made. */
304 /*ARGSUSED*/
305 static bool
306 FuncMake(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
307 {
308 StringListNode *ln;
309
310 for (ln = opts.create.first; ln != NULL; ln = ln->next)
311 if (Str_Match(ln->datum, arg))
312 return true;
313 return false;
314 }
315
316 /* See if the given file exists. */
317 /*ARGSUSED*/
318 static bool
319 FuncExists(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
320 {
321 bool result;
322 char *path;
323
324 path = Dir_FindFile(arg, &dirSearchPath);
325 DEBUG2(COND, "exists(%s) result is \"%s\"\n",
326 arg, path != NULL ? path : "");
327 result = path != NULL;
328 free(path);
329 return result;
330 }
331
332 /* See if the given node exists and is an actual target. */
333 /*ARGSUSED*/
334 static bool
335 FuncTarget(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
336 {
337 GNode *gn = Targ_FindNode(arg);
338 return gn != NULL && GNode_IsTarget(gn);
339 }
340
341 /*
342 * See if the given node exists and is an actual target with commands
343 * associated with it.
344 */
345 /*ARGSUSED*/
346 static bool
347 FuncCommands(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
348 {
349 GNode *gn = Targ_FindNode(arg);
350 return gn != NULL && GNode_IsTarget(gn) && !Lst_IsEmpty(&gn->commands);
351 }
352
353 /*
354 * Convert the given number into a double.
355 * We try a base 10 or 16 integer conversion first, if that fails
356 * then we try a floating point conversion instead.
357 *
358 * Results:
359 * Returns true if the conversion succeeded.
360 * Sets 'out_value' to the converted number.
361 */
362 static bool
363 TryParseNumber(const char *str, double *out_value)
364 {
365 char *end;
366 unsigned long ul_val;
367 double dbl_val;
368
369 if (str[0] == '\0') { /* XXX: why is an empty string a number? */
370 *out_value = 0.0;
371 return true;
372 }
373
374 errno = 0;
375 ul_val = strtoul(str, &end, str[1] == 'x' ? 16 : 10);
376 if (*end == '\0' && errno != ERANGE) {
377 *out_value = str[0] == '-' ? -(double)-ul_val : (double)ul_val;
378 return true;
379 }
380
381 if (*end != '\0' && *end != '.' && *end != 'e' && *end != 'E')
382 return false; /* skip the expensive strtod call */
383 dbl_val = strtod(str, &end);
384 if (*end != '\0')
385 return false;
386
387 *out_value = dbl_val;
388 return true;
389 }
390
391 static bool
392 is_separator(char ch)
393 {
394 return ch == '\0' || ch_isspace(ch) || ch == '!' || ch == '=' ||
395 ch == '>' || ch == '<' || ch == ')' /* but not '(' */;
396 }
397
398 /*
399 * In a quoted or unquoted string literal or a number, parse a variable
400 * expression.
401 *
402 * Example: .if x${CENTER}y == "${PREFIX}${SUFFIX}" || 0x${HEX}
403 */
404 static bool
405 CondParser_StringExpr(CondParser *par, const char *start,
406 bool doEval, bool quoted,
407 Buffer *buf, FStr *inout_str)
408 {
409 VarEvalMode emode;
410 const char *nested_p;
411 bool atStart;
412 VarParseResult parseResult;
413
414 emode = doEval && quoted ? VARE_WANTRES
415 : doEval ? VARE_UNDEFERR
416 : VARE_PARSE_ONLY;
417
418 nested_p = par->p;
419 atStart = nested_p == start;
420 parseResult = Var_Parse(&nested_p, SCOPE_CMDLINE, emode, inout_str);
421 /* TODO: handle errors */
422 if (inout_str->str == var_Error) {
423 if (parseResult == VPR_ERR) {
424 /*
425 * FIXME: Even if an error occurs, there is no
426 * guarantee that it is reported.
427 *
428 * See cond-token-plain.mk $$$$$$$$.
429 */
430 par->printedError = true;
431 }
432 /*
433 * XXX: Can there be any situation in which a returned
434 * var_Error needs to be freed?
435 */
436 FStr_Done(inout_str);
437 /*
438 * Even if !doEval, we still report syntax errors, which is
439 * what getting var_Error back with !doEval means.
440 */
441 *inout_str = FStr_InitRefer(NULL);
442 return false;
443 }
444 par->p = nested_p;
445
446 /*
447 * If the '$' started the string literal (which means no quotes), and
448 * the variable expression is followed by a space, looks like a
449 * comparison operator or is the end of the expression, we are done.
450 */
451 if (atStart && is_separator(par->p[0]))
452 return false;
453
454 Buf_AddStr(buf, inout_str->str);
455 FStr_Done(inout_str);
456 *inout_str = FStr_InitRefer(NULL); /* not finished yet */
457 return true;
458 }
459
460 /*
461 * Parse a string from a variable expression or an optionally quoted
462 * string. This is called for the left-hand and right-hand sides of
463 * comparisons.
464 *
465 * Results:
466 * Returns the string, absent any quotes, or NULL on error.
467 * Sets out_quoted if the leaf was a quoted string literal.
468 */
469 static void
470 CondParser_Leaf(CondParser *par, bool doEval, bool unquotedOK,
471 FStr *out_str, bool *out_quoted)
472 {
473 Buffer buf;
474 FStr str;
475 bool quoted;
476 const char *start;
477
478 Buf_Init(&buf);
479 str = FStr_InitRefer(NULL);
480 *out_quoted = quoted = par->p[0] == '"';
481 start = par->p;
482 if (quoted)
483 par->p++;
484
485 while (par->p[0] != '\0' && str.str == NULL) {
486 switch (par->p[0]) {
487 case '\\':
488 par->p++;
489 if (par->p[0] != '\0') {
490 Buf_AddByte(&buf, par->p[0]);
491 par->p++;
492 }
493 continue;
494 case '"':
495 par->p++;
496 if (quoted)
497 goto got_str; /* skip the closing quote */
498 Buf_AddByte(&buf, '"');
499 continue;
500 case ')': /* see is_separator */
501 case '!':
502 case '=':
503 case '>':
504 case '<':
505 case ' ':
506 case '\t':
507 if (!quoted)
508 goto got_str;
509 Buf_AddByte(&buf, par->p[0]);
510 par->p++;
511 continue;
512 case '$':
513 if (!CondParser_StringExpr(par,
514 start, doEval, quoted, &buf, &str))
515 goto cleanup;
516 continue;
517 default:
518 if (!unquotedOK && !quoted && *start != '$' &&
519 !ch_isdigit(*start)) {
520 /*
521 * The left-hand side must be quoted,
522 * a variable expression or a number.
523 */
524 str = FStr_InitRefer(NULL);
525 goto cleanup;
526 }
527 Buf_AddByte(&buf, par->p[0]);
528 par->p++;
529 continue;
530 }
531 }
532 got_str:
533 str = FStr_InitOwn(buf.data);
534 cleanup:
535 Buf_DoneData(&buf); /* XXX: memory leak on failure? */
536 *out_str = str;
537 }
538
539 static bool
540 EvalBare(const CondParser *par, const char *arg, size_t arglen)
541 {
542 bool res = par->evalBare(arglen, arg);
543 return par->negateEvalBare ? !res : res;
544 }
545
546 /*
547 * Evaluate a "comparison without operator", such as in ".if ${VAR}" or
548 * ".if 0".
549 */
550 static bool
551 EvalNotEmpty(CondParser *par, const char *value, bool quoted)
552 {
553 double num;
554
555 /* For .ifxxx "...", check for non-empty string. */
556 if (quoted)
557 return value[0] != '\0';
558
559 /* For .ifxxx <number>, compare against zero */
560 if (TryParseNumber(value, &num))
561 return num != 0.0;
562
563 /* For .if ${...}, check for non-empty string. This is different from
564 * the evaluation function from that .if variant, which would test
565 * whether a variable of the given name were defined. */
566 /* XXX: Whitespace should count as empty, just as in ParseEmptyArg. */
567 if (par->plain)
568 return value[0] != '\0';
569
570 return EvalBare(par, value, strlen(value));
571 }
572
573 /* Evaluate a numerical comparison, such as in ".if ${VAR} >= 9". */
574 static bool
575 EvalCompareNum(double lhs, ComparisonOp op, double rhs)
576 {
577 DEBUG3(COND, "lhs = %f, rhs = %f, op = %.2s\n", lhs, rhs, opname[op]);
578
579 switch (op) {
580 case LT:
581 return lhs < rhs;
582 case LE:
583 return lhs <= rhs;
584 case GT:
585 return lhs > rhs;
586 case GE:
587 return lhs >= rhs;
588 case NE:
589 return lhs != rhs;
590 default:
591 return lhs == rhs;
592 }
593 }
594
595 static Token
596 EvalCompareStr(CondParser *par, const char *lhs,
597 ComparisonOp op, const char *rhs)
598 {
599 if (op != EQ && op != NE) {
600 Parse_Error(PARSE_FATAL,
601 "String comparison operator must be either == or !=");
602 par->printedError = true;
603 return TOK_ERROR;
604 }
605
606 DEBUG3(COND, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
607 lhs, rhs, opname[op]);
608 return ToToken((op == EQ) == (strcmp(lhs, rhs) == 0));
609 }
610
611 /* Evaluate a comparison, such as "${VAR} == 12345". */
612 static Token
613 EvalCompare(CondParser *par, const char *lhs, bool lhsQuoted,
614 ComparisonOp op, const char *rhs, bool rhsQuoted)
615 {
616 double left, right;
617
618 if (!rhsQuoted && !lhsQuoted)
619 if (TryParseNumber(lhs, &left) && TryParseNumber(rhs, &right))
620 return ToToken(EvalCompareNum(left, op, right));
621
622 return EvalCompareStr(par, lhs, op, rhs);
623 }
624
625 static bool
626 CondParser_ComparisonOp(CondParser *par, ComparisonOp *out_op)
627 {
628 const char *p = par->p;
629
630 if (p[0] == '<' && p[1] == '=') {
631 *out_op = LE;
632 goto length_2;
633 } else if (p[0] == '<') {
634 *out_op = LT;
635 goto length_1;
636 } else if (p[0] == '>' && p[1] == '=') {
637 *out_op = GE;
638 goto length_2;
639 } else if (p[0] == '>') {
640 *out_op = GT;
641 goto length_1;
642 } else if (p[0] == '=' && p[1] == '=') {
643 *out_op = EQ;
644 goto length_2;
645 } else if (p[0] == '!' && p[1] == '=') {
646 *out_op = NE;
647 goto length_2;
648 }
649 return false;
650
651 length_2:
652 par->p = p + 2;
653 return true;
654 length_1:
655 par->p = p + 1;
656 return true;
657 }
658
659 /*
660 * Parse a comparison condition such as:
661 *
662 * 0
663 * ${VAR:Mpattern}
664 * ${VAR} == value
665 * ${VAR:U0} < 12345
666 */
667 static Token
668 CondParser_Comparison(CondParser *par, bool doEval)
669 {
670 Token t = TOK_ERROR;
671 FStr lhs, rhs;
672 ComparisonOp op;
673 bool lhsQuoted, rhsQuoted;
674
675 CondParser_Leaf(par, doEval, par->leftUnquotedOK, &lhs, &lhsQuoted);
676 if (lhs.str == NULL)
677 goto done_lhs;
678
679 CondParser_SkipWhitespace(par);
680
681 if (!CondParser_ComparisonOp(par, &op)) {
682 /* Unknown operator, compare against an empty string or 0. */
683 t = ToToken(doEval && EvalNotEmpty(par, lhs.str, lhsQuoted));
684 goto done_lhs;
685 }
686
687 CondParser_SkipWhitespace(par);
688
689 if (par->p[0] == '\0') {
690 Parse_Error(PARSE_FATAL,
691 "Missing right-hand side of operator '%s'", opname[op]);
692 par->printedError = true;
693 goto done_lhs;
694 }
695
696 CondParser_Leaf(par, doEval, true, &rhs, &rhsQuoted);
697 if (rhs.str == NULL)
698 goto done_rhs;
699
700 if (!doEval) {
701 t = TOK_FALSE;
702 goto done_rhs;
703 }
704
705 t = EvalCompare(par, lhs.str, lhsQuoted, op, rhs.str, rhsQuoted);
706
707 done_rhs:
708 FStr_Done(&rhs);
709 done_lhs:
710 FStr_Done(&lhs);
711 return t;
712 }
713
714 /*
715 * The argument to empty() is a variable name, optionally followed by
716 * variable modifiers.
717 */
718 static Token
719 ParseEmptyArg(const char **pp, bool doEval)
720 {
721 FStr val;
722 Token tok;
723
724 (*pp)--; /* Make (*pp)[1] point to the '('. */
725 (void)Var_Parse(pp, SCOPE_CMDLINE,
726 doEval ? VARE_WANTRES : VARE_PARSE_ONLY, &val);
727 /* TODO: handle errors */
728 /* If successful, *pp points beyond the closing ')' now. */
729
730 if (val.str == var_Error)
731 tok = TOK_ERROR;
732 else {
733 cpp_skip_whitespace(&val.str);
734 tok = val.str[0] != '\0' ? TOK_FALSE : TOK_TRUE;
735 }
736
737 FStr_Done(&val);
738 return tok;
739 }
740
741 static bool
742 CondParser_FuncCallEmpty(CondParser *par, bool doEval, Token *out_token)
743 {
744 Token tok;
745 const char *cp = par->p;
746
747 if (!is_token(cp, "empty", 5))
748 return false;
749 cp += 5;
750
751 cpp_skip_whitespace(&cp);
752 if (*cp != '(')
753 return false;
754
755 tok = ParseEmptyArg(&cp, doEval);
756 if (tok == TOK_FALSE && !doEval)
757 tok = TOK_TRUE;
758 *out_token = tok;
759 par->p = cp;
760 return true;
761 }
762
763 /* Parse a function call expression, such as 'defined(${file})'. */
764 static bool
765 CondParser_FuncCall(CondParser *par, bool doEval, Token *out_token)
766 {
767 static const struct fn_def {
768 const char fn_name[9];
769 unsigned char fn_name_len;
770 bool (*fn_eval)(size_t, const char *);
771 } fns[] = {
772 { "defined", 7, FuncDefined },
773 { "make", 4, FuncMake },
774 { "exists", 6, FuncExists },
775 { "target", 6, FuncTarget },
776 { "commands", 8, FuncCommands }
777 };
778 const struct fn_def *fn;
779 char *arg = NULL;
780 size_t arglen;
781 const char *cp = par->p;
782 const struct fn_def *last_fn = fns + sizeof fns / sizeof fns[0] - 1;
783
784 for (fn = fns; !is_token(cp, fn->fn_name, fn->fn_name_len); fn++)
785 if (fn == last_fn)
786 return false;
787
788 cp += fn->fn_name_len;
789 cpp_skip_whitespace(&cp);
790 if (*cp != '(')
791 return false;
792
793 arglen = ParseFuncArg(par, &cp, doEval, fn->fn_name, &arg);
794 if (arglen == 0 || arglen == (size_t)-1) {
795 par->p = cp;
796 *out_token = arglen == 0 ? TOK_FALSE : TOK_ERROR;
797 return true;
798 }
799
800 /* Evaluate the argument using the required function. */
801 *out_token = ToToken(!doEval || fn->fn_eval(arglen, arg));
802 free(arg);
803 par->p = cp;
804 return true;
805 }
806
807 /*
808 * Parse a comparison such as '${VAR} == "value"', or a simple leaf without
809 * operator, which is a number, a variable expression or a string literal.
810 */
811 static Token
812 CondParser_ComparisonOrLeaf(CondParser *par, bool doEval)
813 {
814 Token t;
815 char *arg = NULL;
816 size_t arglen;
817 const char *cp;
818 const char *cp1;
819
820 /* Push anything numeric through the compare expression */
821 cp = par->p;
822 if (ch_isdigit(cp[0]) || cp[0] == '-' || cp[0] == '+')
823 return CondParser_Comparison(par, doEval);
824
825 /*
826 * Most likely we have a naked token to apply the default function to.
827 * However ".if a == b" gets here when the "a" is unquoted and doesn't
828 * start with a '$'. This surprises people.
829 * If what follows the function argument is a '=' or '!' then the
830 * syntax would be invalid if we did "defined(a)" - so instead treat
831 * as an expression.
832 */
833 /*
834 * XXX: Is it possible to have a variable expression evaluated twice
835 * at this point?
836 */
837 arglen = ParseFuncArg(par, &cp, doEval, NULL, &arg);
838 cp1 = cp;
839 cpp_skip_whitespace(&cp1);
840 if (*cp1 == '=' || *cp1 == '!' || *cp1 == '<' || *cp1 == '>')
841 return CondParser_Comparison(par, doEval);
842 par->p = cp;
843
844 /*
845 * Evaluate the argument using the default function.
846 * This path always treats .if as .ifdef. To get here, the character
847 * after .if must have been taken literally, so the argument cannot
848 * be empty - even if it contained a variable expansion.
849 */
850 t = ToToken(!doEval || EvalBare(par, arg, arglen));
851 free(arg);
852 return t;
853 }
854
855 /* Return the next token or comparison result from the parser. */
856 static Token
857 CondParser_Token(CondParser *par, bool doEval)
858 {
859 Token t;
860
861 t = par->curr;
862 if (t != TOK_NONE) {
863 par->curr = TOK_NONE;
864 return t;
865 }
866
867 cpp_skip_hspace(&par->p);
868
869 switch (par->p[0]) {
870
871 case '(':
872 par->p++;
873 return TOK_LPAREN;
874
875 case ')':
876 par->p++;
877 return TOK_RPAREN;
878
879 case '|':
880 par->p++;
881 if (par->p[0] == '|')
882 par->p++;
883 else if (opts.strict) {
884 Parse_Error(PARSE_FATAL, "Unknown operator '|'");
885 par->printedError = true;
886 return TOK_ERROR;
887 }
888 return TOK_OR;
889
890 case '&':
891 par->p++;
892 if (par->p[0] == '&')
893 par->p++;
894 else if (opts.strict) {
895 Parse_Error(PARSE_FATAL, "Unknown operator '&'");
896 par->printedError = true;
897 return TOK_ERROR;
898 }
899 return TOK_AND;
900
901 case '!':
902 par->p++;
903 return TOK_NOT;
904
905 case '#': /* XXX: see unit-tests/cond-token-plain.mk */
906 case '\n': /* XXX: why should this end the condition? */
907 /* Probably obsolete now, from 1993-03-21. */
908 case '\0':
909 return TOK_EOF;
910
911 case '"':
912 case '$':
913 return CondParser_Comparison(par, doEval);
914
915 default:
916 if (CondParser_FuncCallEmpty(par, doEval, &t))
917 return t;
918 if (CondParser_FuncCall(par, doEval, &t))
919 return t;
920 return CondParser_ComparisonOrLeaf(par, doEval);
921 }
922 }
923
924 /* Skip the next token if it equals t. */
925 static bool
926 CondParser_Skip(CondParser *par, Token t)
927 {
928 Token actual;
929
930 actual = CondParser_Token(par, false);
931 if (actual == t)
932 return true;
933
934 assert(par->curr == TOK_NONE);
935 assert(actual != TOK_NONE);
936 par->curr = actual;
937 return false;
938 }
939
940 /*
941 * Term -> '(' Or ')'
942 * Term -> '!' Term
943 * Term -> Leaf Operator Leaf
944 * Term -> Leaf
945 */
946 static CondResult
947 CondParser_Term(CondParser *par, bool doEval)
948 {
949 CondResult res;
950 Token t;
951
952 t = CondParser_Token(par, doEval);
953 if (t == TOK_TRUE)
954 return CR_TRUE;
955 if (t == TOK_FALSE)
956 return CR_FALSE;
957
958 if (t == TOK_LPAREN) {
959 res = CondParser_Or(par, doEval);
960 if (res == CR_ERROR)
961 return CR_ERROR;
962 if (CondParser_Token(par, doEval) != TOK_RPAREN)
963 return CR_ERROR;
964 return res;
965 }
966
967 if (t == TOK_NOT) {
968 res = CondParser_Term(par, doEval);
969 if (res == CR_TRUE)
970 res = CR_FALSE;
971 else if (res == CR_FALSE)
972 res = CR_TRUE;
973 return res;
974 }
975
976 return CR_ERROR;
977 }
978
979 /*
980 * And -> Term ('&&' Term)*
981 */
982 static CondResult
983 CondParser_And(CondParser *par, bool doEval)
984 {
985 CondResult res, rhs;
986
987 res = CR_TRUE;
988 do {
989 if ((rhs = CondParser_Term(par, doEval)) == CR_ERROR)
990 return CR_ERROR;
991 if (rhs == CR_FALSE) {
992 res = CR_FALSE;
993 doEval = false;
994 }
995 } while (CondParser_Skip(par, TOK_AND));
996
997 return res;
998 }
999
1000 /*
1001 * Or -> And ('||' And)*
1002 */
1003 static CondResult
1004 CondParser_Or(CondParser *par, bool doEval)
1005 {
1006 CondResult res, rhs;
1007
1008 res = CR_FALSE;
1009 do {
1010 if ((rhs = CondParser_And(par, doEval)) == CR_ERROR)
1011 return CR_ERROR;
1012 if (rhs == CR_TRUE) {
1013 res = CR_TRUE;
1014 doEval = false;
1015 }
1016 } while (CondParser_Skip(par, TOK_OR));
1017
1018 return res;
1019 }
1020
1021 static CondEvalResult
1022 CondParser_Eval(CondParser *par, bool *out_value)
1023 {
1024 CondResult res;
1025
1026 DEBUG1(COND, "CondParser_Eval: %s\n", par->p);
1027
1028 res = CondParser_Or(par, true);
1029 if (res == CR_ERROR)
1030 return COND_INVALID;
1031
1032 if (CondParser_Token(par, false) != TOK_EOF)
1033 return COND_INVALID;
1034
1035 *out_value = res == CR_TRUE;
1036 return COND_PARSE;
1037 }
1038
1039 /*
1040 * Evaluate the condition, including any side effects from the variable
1041 * expressions in the condition. The condition consists of &&, ||, !,
1042 * function(arg), comparisons and parenthetical groupings thereof.
1043 *
1044 * Results:
1045 * COND_PARSE if the condition was valid grammatically
1046 * COND_INVALID if not a valid conditional.
1047 *
1048 * *out_value is set to the boolean value of the condition
1049 */
1050 static CondEvalResult
1051 CondEvalExpression(const char *cond, bool *out_value, bool plain,
1052 bool (*evalBare)(size_t, const char *), bool negate,
1053 bool eprint, bool leftUnquotedOK)
1054 {
1055 CondParser par;
1056 CondEvalResult rval;
1057
1058 cpp_skip_hspace(&cond);
1059
1060 par.plain = plain;
1061 par.evalBare = evalBare;
1062 par.negateEvalBare = negate;
1063 par.leftUnquotedOK = leftUnquotedOK;
1064 par.p = cond;
1065 par.curr = TOK_NONE;
1066 par.printedError = false;
1067
1068 rval = CondParser_Eval(&par, out_value);
1069
1070 if (rval == COND_INVALID && eprint && !par.printedError)
1071 Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", cond);
1072
1073 return rval;
1074 }
1075
1076 /*
1077 * Evaluate a condition in a :? modifier, such as
1078 * ${"${VAR}" == value:?yes:no}.
1079 */
1080 CondEvalResult
1081 Cond_EvalCondition(const char *cond, bool *out_value)
1082 {
1083 return CondEvalExpression(cond, out_value, true,
1084 FuncDefined, false, false, true);
1085 }
1086
1087 static bool
1088 IsEndif(const char *p)
1089 {
1090 return p[0] == 'e' && p[1] == 'n' && p[2] == 'd' &&
1091 p[3] == 'i' && p[4] == 'f' && !ch_isalpha(p[5]);
1092 }
1093
1094 static bool
1095 DetermineKindOfConditional(const char **pp, bool *out_plain,
1096 bool (**out_evalBare)(size_t, const char *),
1097 bool *out_negate)
1098 {
1099 const char *p = *pp;
1100
1101 p += 2;
1102 *out_plain = false;
1103 *out_evalBare = FuncDefined;
1104 *out_negate = false;
1105 if (*p == 'n') {
1106 p++;
1107 *out_negate = true;
1108 }
1109 if (is_token(p, "def", 3)) { /* .ifdef and .ifndef */
1110 p += 3;
1111 } else if (is_token(p, "make", 4)) { /* .ifmake and .ifnmake */
1112 p += 4;
1113 *out_evalBare = FuncMake;
1114 } else if (is_token(p, "", 0) && !*out_negate) { /* plain .if */
1115 *out_plain = true;
1116 } else {
1117 /*
1118 * TODO: Add error message about unknown directive,
1119 * since there is no other known directive that starts
1120 * with 'el' or 'if'.
1121 *
1122 * Example: .elifx 123
1123 */
1124 return false;
1125 }
1126
1127 *pp = p;
1128 return true;
1129 }
1130
1131 /*
1132 * Evaluate the conditional directive in the line, which is one of:
1133 *
1134 * .if <cond>
1135 * .ifmake <cond>
1136 * .ifnmake <cond>
1137 * .ifdef <cond>
1138 * .ifndef <cond>
1139 * .elif <cond>
1140 * .elifmake <cond>
1141 * .elifnmake <cond>
1142 * .elifdef <cond>
1143 * .elifndef <cond>
1144 * .else
1145 * .endif
1146 *
1147 * In these directives, <cond> consists of &&, ||, !, function(arg),
1148 * comparisons, expressions, bare words, numbers and strings, and
1149 * parenthetical groupings thereof.
1150 *
1151 * Results:
1152 * COND_PARSE to continue parsing the lines that follow the
1153 * conditional (when <cond> evaluates to true)
1154 * COND_SKIP to skip the lines after the conditional
1155 * (when <cond> evaluates to false, or when a previous
1156 * branch has already been taken)
1157 * COND_INVALID if the conditional was not valid, either because of
1158 * a syntax error or because some variable was undefined
1159 * or because the condition could not be evaluated
1160 */
1161 CondEvalResult
1162 Cond_EvalLine(const char *line)
1163 {
1164 typedef enum IfState {
1165
1166 /* None of the previous <cond> evaluated to true. */
1167 IFS_INITIAL = 0,
1168
1169 /* The previous <cond> evaluated to true.
1170 * The lines following this condition are interpreted. */
1171 IFS_ACTIVE = 1 << 0,
1172
1173 /* The previous directive was an '.else'. */
1174 IFS_SEEN_ELSE = 1 << 1,
1175
1176 /* One of the previous <cond> evaluated to true. */
1177 IFS_WAS_ACTIVE = 1 << 2
1178
1179 } IfState;
1180
1181 static enum IfState *cond_states = NULL;
1182 static unsigned int cond_states_cap = 128;
1183
1184 bool plain;
1185 bool (*evalBare)(size_t, const char *);
1186 bool negate;
1187 bool isElif;
1188 bool value;
1189 IfState state;
1190 const char *p = line;
1191
1192 if (cond_states == NULL) {
1193 cond_states = bmake_malloc(
1194 cond_states_cap * sizeof *cond_states);
1195 cond_states[0] = IFS_ACTIVE;
1196 }
1197
1198 p++; /* skip the leading '.' */
1199 cpp_skip_hspace(&p);
1200
1201 if (IsEndif(p)) { /* It is an '.endif'. */
1202 if (p[5] != '\0') {
1203 Parse_Error(PARSE_FATAL,
1204 "The .endif directive does not take arguments");
1205 }
1206
1207 if (cond_depth == cond_min_depth) {
1208 Parse_Error(PARSE_FATAL, "if-less endif");
1209 return COND_PARSE;
1210 }
1211
1212 /* Return state for previous conditional */
1213 cond_depth--;
1214 return cond_states[cond_depth] & IFS_ACTIVE
1215 ? COND_PARSE : COND_SKIP;
1216 }
1217
1218 /* Parse the name of the directive, such as 'if', 'elif', 'endif'. */
1219 if (p[0] == 'e') {
1220 if (p[1] != 'l') {
1221 /*
1222 * Unknown directive. It might still be a
1223 * transformation rule like '.err.txt',
1224 * therefore no error message here.
1225 */
1226 return COND_INVALID;
1227 }
1228
1229 /* Quite likely this is 'else' or 'elif' */
1230 p += 2;
1231 if (is_token(p, "se", 2)) { /* It is an 'else'. */
1232
1233 if (p[2] != '\0')
1234 Parse_Error(PARSE_FATAL,
1235 "The .else directive "
1236 "does not take arguments");
1237
1238 if (cond_depth == cond_min_depth) {
1239 Parse_Error(PARSE_FATAL, "if-less else");
1240 return COND_PARSE;
1241 }
1242
1243 state = cond_states[cond_depth];
1244 if (state == IFS_INITIAL) {
1245 state = IFS_ACTIVE | IFS_SEEN_ELSE;
1246 } else {
1247 if (state & IFS_SEEN_ELSE)
1248 Parse_Error(PARSE_WARNING,
1249 "extra else");
1250 state = IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
1251 }
1252 cond_states[cond_depth] = state;
1253
1254 return state & IFS_ACTIVE ? COND_PARSE : COND_SKIP;
1255 }
1256 /* Assume for now it is an elif */
1257 isElif = true;
1258 } else
1259 isElif = false;
1260
1261 if (p[0] != 'i' || p[1] != 'f') {
1262 /*
1263 * Unknown directive. It might still be a transformation rule
1264 * like '.elisp.scm', therefore no error message here.
1265 */
1266 return COND_INVALID; /* Not an ifxxx or elifxxx line */
1267 }
1268
1269 if (!DetermineKindOfConditional(&p, &plain, &evalBare, &negate))
1270 return COND_INVALID;
1271
1272 if (isElif) {
1273 if (cond_depth == cond_min_depth) {
1274 Parse_Error(PARSE_FATAL, "if-less elif");
1275 return COND_PARSE;
1276 }
1277 state = cond_states[cond_depth];
1278 if (state & IFS_SEEN_ELSE) {
1279 Parse_Error(PARSE_WARNING, "extra elif");
1280 cond_states[cond_depth] =
1281 IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
1282 return COND_SKIP;
1283 }
1284 if (state != IFS_INITIAL) {
1285 cond_states[cond_depth] = IFS_WAS_ACTIVE;
1286 return COND_SKIP;
1287 }
1288 } else {
1289 /* Normal .if */
1290 if (cond_depth + 1 >= cond_states_cap) {
1291 /*
1292 * This is rare, but not impossible.
1293 * In meta mode, dirdeps.mk (only runs at level 0)
1294 * can need more than the default.
1295 */
1296 cond_states_cap += 32;
1297 cond_states = bmake_realloc(cond_states,
1298 cond_states_cap *
1299 sizeof *cond_states);
1300 }
1301 state = cond_states[cond_depth];
1302 cond_depth++;
1303 if (!(state & IFS_ACTIVE)) {
1304 /*
1305 * If we aren't parsing the data,
1306 * treat as always false.
1307 */
1308 cond_states[cond_depth] = IFS_WAS_ACTIVE;
1309 return COND_SKIP;
1310 }
1311 }
1312
1313 /* And evaluate the conditional expression */
1314 if (CondEvalExpression(p, &value, plain, evalBare, negate,
1315 true, false) == COND_INVALID) {
1316 /* Syntax error in conditional, error message already output. */
1317 /* Skip everything to matching .endif */
1318 /* XXX: An extra '.else' is not detected in this case. */
1319 cond_states[cond_depth] = IFS_WAS_ACTIVE;
1320 return COND_SKIP;
1321 }
1322
1323 if (!value) {
1324 cond_states[cond_depth] = IFS_INITIAL;
1325 return COND_SKIP;
1326 }
1327 cond_states[cond_depth] = IFS_ACTIVE;
1328 return COND_PARSE;
1329 }
1330
1331 void
1332 Cond_restore_depth(unsigned int saved_depth)
1333 {
1334 unsigned int open_conds = cond_depth - cond_min_depth;
1335
1336 if (open_conds != 0 || saved_depth > cond_depth) {
1337 Parse_Error(PARSE_FATAL, "%u open conditional%s",
1338 open_conds, open_conds == 1 ? "" : "s");
1339 cond_depth = cond_min_depth;
1340 }
1341
1342 cond_min_depth = saved_depth;
1343 }
1344
1345 unsigned int
1346 Cond_save_depth(void)
1347 {
1348 unsigned int depth = cond_min_depth;
1349
1350 cond_min_depth = cond_depth;
1351 return depth;
1352 }
1353