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