cond.c revision 1.301 1 /* $NetBSD: cond.c,v 1.301 2021/12/12 08:55:28 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.301 2021/12/12 08:55:28 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)(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 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 * Arguments:
213 * *pp initially points at the '(',
214 * upon successful return it points right after the ')'.
215 *
216 * *out_arg receives the argument as string.
217 *
218 * func says whether the argument belongs to an actual function, or
219 * NULL when parsing a bare word.
220 *
221 * Return the length of the argument, or an ambiguous 0 on error.
222 */
223 static size_t
224 ParseWord(CondParser *par, const char **pp, bool doEval, const char *func,
225 char **out_arg)
226 {
227 const char *p = *pp;
228 Buffer argBuf;
229 int paren_depth;
230 size_t argLen;
231
232 if (func != NULL)
233 p++; /* Skip opening '(' - verified by caller */
234
235 cpp_skip_hspace(&p);
236
237 Buf_InitSize(&argBuf, 16);
238
239 paren_depth = 0;
240 for (;;) {
241 char ch = *p;
242 if (ch == '\0' || ch == ' ' || ch == '\t')
243 break;
244 if ((ch == '&' || ch == '|') && paren_depth == 0)
245 break;
246 if (*p == '$') {
247 /*
248 * Parse the variable expression and install it as
249 * part of the argument if it's valid. We tell
250 * Var_Parse to complain on an undefined variable,
251 * (XXX: but Var_Parse ignores that request)
252 * so we don't need to do it. Nor do we return an
253 * error, though perhaps we should.
254 */
255 VarEvalMode emode = doEval
256 ? VARE_UNDEFERR
257 : VARE_PARSE_ONLY;
258 FStr nestedVal;
259 (void)Var_Parse(&p, SCOPE_CMDLINE, emode, &nestedVal);
260 /* TODO: handle errors */
261 Buf_AddStr(&argBuf, nestedVal.str);
262 FStr_Done(&nestedVal);
263 continue;
264 }
265 if (ch == '(')
266 paren_depth++;
267 else if (ch == ')' && --paren_depth < 0)
268 break;
269 Buf_AddByte(&argBuf, *p);
270 p++;
271 }
272
273 argLen = argBuf.len;
274 *out_arg = Buf_DoneData(&argBuf);
275
276 cpp_skip_hspace(&p);
277
278 if (func != NULL && *p++ != ')') {
279 Parse_Error(PARSE_FATAL,
280 "Missing closing parenthesis for %s()", func);
281 par->printedError = true;
282 return 0;
283 }
284
285 *pp = p;
286 return argLen;
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 *nested_p;
403 bool atStart;
404 VarParseResult parseResult;
405
406 emode = doEval && quoted ? VARE_WANTRES
407 : doEval ? VARE_UNDEFERR
408 : VARE_PARSE_ONLY;
409
410 nested_p = par->p;
411 atStart = nested_p == start;
412 parseResult = Var_Parse(&nested_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 = nested_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
454 * string. This is called for the left-hand and right-hand sides of
455 * comparisons.
456 *
457 * Results:
458 * Returns the string, absent any quotes, or NULL on error.
459 * Sets out_quoted if the leaf was a quoted string literal.
460 */
461 static void
462 CondParser_Leaf(CondParser *par, bool doEval, bool unquotedOK,
463 FStr *out_str, bool *out_quoted)
464 {
465 Buffer buf;
466 FStr str;
467 bool quoted;
468 const char *start;
469
470 Buf_Init(&buf);
471 str = FStr_InitRefer(NULL);
472 *out_quoted = quoted = par->p[0] == '"';
473 start = par->p;
474 if (quoted)
475 par->p++;
476
477 while (par->p[0] != '\0' && str.str == NULL) {
478 switch (par->p[0]) {
479 case '\\':
480 par->p++;
481 if (par->p[0] != '\0') {
482 Buf_AddByte(&buf, par->p[0]);
483 par->p++;
484 }
485 continue;
486 case '"':
487 par->p++;
488 if (quoted)
489 goto got_str; /* skip the closing quote */
490 Buf_AddByte(&buf, '"');
491 continue;
492 case ')': /* see is_separator */
493 case '!':
494 case '=':
495 case '>':
496 case '<':
497 case ' ':
498 case '\t':
499 if (!quoted)
500 goto got_str;
501 Buf_AddByte(&buf, par->p[0]);
502 par->p++;
503 continue;
504 case '$':
505 if (!CondParser_StringExpr(par,
506 start, doEval, quoted, &buf, &str))
507 goto cleanup;
508 continue;
509 default:
510 if (!unquotedOK && !quoted && *start != '$' &&
511 !ch_isdigit(*start)) {
512 /*
513 * The left-hand side must be quoted,
514 * a variable expression or a number.
515 */
516 str = FStr_InitRefer(NULL);
517 goto cleanup;
518 }
519 Buf_AddByte(&buf, par->p[0]);
520 par->p++;
521 continue;
522 }
523 }
524 got_str:
525 str = FStr_InitOwn(buf.data);
526 cleanup:
527 Buf_DoneData(&buf); /* XXX: memory leak on failure? */
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 /* For .if ${...}, check for non-empty string. This is different from
556 * the evaluation function from that .if variant, which would test
557 * whether a variable of the given name were defined. */
558 /*
559 * XXX: Whitespace should count as empty, just as in
560 * CondParser_FuncCallEmpty.
561 */
562 if (par->plain)
563 return value[0] != '\0';
564
565 return EvalBare(par, value);
566 }
567
568 /* Evaluate a numerical comparison, such as in ".if ${VAR} >= 9". */
569 static bool
570 EvalCompareNum(double lhs, ComparisonOp op, double rhs)
571 {
572 DEBUG3(COND, "lhs = %f, rhs = %f, op = %.2s\n", lhs, rhs, opname[op]);
573
574 switch (op) {
575 case LT:
576 return lhs < rhs;
577 case LE:
578 return lhs <= rhs;
579 case GT:
580 return lhs > rhs;
581 case GE:
582 return lhs >= rhs;
583 case NE:
584 return lhs != rhs;
585 default:
586 return lhs == rhs;
587 }
588 }
589
590 static Token
591 EvalCompareStr(CondParser *par, const char *lhs,
592 ComparisonOp op, const char *rhs)
593 {
594 if (op != EQ && op != NE) {
595 Parse_Error(PARSE_FATAL,
596 "String comparison operator must be either == or !=");
597 par->printedError = true;
598 return TOK_ERROR;
599 }
600
601 DEBUG3(COND, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
602 lhs, rhs, opname[op]);
603 return ToToken((op == EQ) == (strcmp(lhs, rhs) == 0));
604 }
605
606 /* Evaluate a comparison, such as "${VAR} == 12345". */
607 static Token
608 EvalCompare(CondParser *par, const char *lhs, bool lhsQuoted,
609 ComparisonOp op, const char *rhs, bool rhsQuoted)
610 {
611 double left, right;
612
613 if (!rhsQuoted && !lhsQuoted)
614 if (TryParseNumber(lhs, &left) && TryParseNumber(rhs, &right))
615 return ToToken(EvalCompareNum(left, op, right));
616
617 return EvalCompareStr(par, lhs, op, rhs);
618 }
619
620 static bool
621 CondParser_ComparisonOp(CondParser *par, ComparisonOp *out_op)
622 {
623 const char *p = par->p;
624
625 if (p[0] == '<' && p[1] == '=') {
626 *out_op = LE;
627 goto length_2;
628 } else if (p[0] == '<') {
629 *out_op = LT;
630 goto length_1;
631 } else if (p[0] == '>' && p[1] == '=') {
632 *out_op = GE;
633 goto length_2;
634 } else if (p[0] == '>') {
635 *out_op = GT;
636 goto length_1;
637 } else if (p[0] == '=' && p[1] == '=') {
638 *out_op = EQ;
639 goto length_2;
640 } else if (p[0] == '!' && p[1] == '=') {
641 *out_op = NE;
642 goto length_2;
643 }
644 return false;
645
646 length_2:
647 par->p = p + 2;
648 return true;
649 length_1:
650 par->p = p + 1;
651 return true;
652 }
653
654 /*
655 * Parse a comparison condition such as:
656 *
657 * 0
658 * ${VAR:Mpattern}
659 * ${VAR} == value
660 * ${VAR:U0} < 12345
661 */
662 static Token
663 CondParser_Comparison(CondParser *par, bool doEval)
664 {
665 Token t = TOK_ERROR;
666 FStr lhs, rhs;
667 ComparisonOp op;
668 bool lhsQuoted, rhsQuoted;
669
670 CondParser_Leaf(par, doEval, par->leftUnquotedOK, &lhs, &lhsQuoted);
671 if (lhs.str == NULL)
672 goto done_lhs;
673
674 CondParser_SkipWhitespace(par);
675
676 if (!CondParser_ComparisonOp(par, &op)) {
677 /* Unknown operator, compare against an empty string or 0. */
678 t = ToToken(doEval && EvalNotEmpty(par, lhs.str, lhsQuoted));
679 goto done_lhs;
680 }
681
682 CondParser_SkipWhitespace(par);
683
684 if (par->p[0] == '\0') {
685 Parse_Error(PARSE_FATAL,
686 "Missing right-hand side of operator '%s'", opname[op]);
687 par->printedError = true;
688 goto done_lhs;
689 }
690
691 CondParser_Leaf(par, doEval, true, &rhs, &rhsQuoted);
692 if (rhs.str == NULL)
693 goto done_rhs;
694
695 if (!doEval) {
696 t = TOK_FALSE;
697 goto done_rhs;
698 }
699
700 t = EvalCompare(par, lhs.str, lhsQuoted, op, rhs.str, rhsQuoted);
701
702 done_rhs:
703 FStr_Done(&rhs);
704 done_lhs:
705 FStr_Done(&lhs);
706 return t;
707 }
708
709 /*
710 * The argument to empty() is a variable name, optionally followed by
711 * variable modifiers.
712 */
713 static bool
714 CondParser_FuncCallEmpty(CondParser *par, bool doEval, Token *out_token)
715 {
716 const char *cp = par->p;
717 Token tok;
718 FStr val;
719
720 if (!is_token(cp, "empty", 5))
721 return false;
722 cp += 5;
723
724 cpp_skip_whitespace(&cp);
725 if (*cp != '(')
726 return false;
727
728 cp--; /* Make cp[1] point to the '('. */
729 (void)Var_Parse(&cp, SCOPE_CMDLINE,
730 doEval ? VARE_WANTRES : VARE_PARSE_ONLY, &val);
731 /* TODO: handle errors */
732
733 if (val.str == var_Error)
734 tok = TOK_ERROR;
735 else {
736 cpp_skip_whitespace(&val.str);
737 tok = val.str[0] != '\0' && doEval ? TOK_FALSE : TOK_TRUE;
738 }
739
740 FStr_Done(&val);
741 *out_token = tok;
742 par->p = cp;
743 return true;
744 }
745
746 /* Parse a function call expression, such as 'defined(${file})'. */
747 static bool
748 CondParser_FuncCall(CondParser *par, bool doEval, Token *out_token)
749 {
750 static const struct fn_def {
751 const char fn_name[9];
752 unsigned char fn_name_len;
753 bool (*fn_eval)(const char *);
754 } fns[] = {
755 { "defined", 7, FuncDefined },
756 { "make", 4, FuncMake },
757 { "exists", 6, FuncExists },
758 { "target", 6, FuncTarget },
759 { "commands", 8, FuncCommands }
760 };
761 const struct fn_def *fn;
762 char *arg = NULL;
763 size_t arglen;
764 const char *cp = par->p;
765 const struct fn_def *last_fn = fns + sizeof fns / sizeof fns[0] - 1;
766
767 for (fn = fns; !is_token(cp, fn->fn_name, fn->fn_name_len); fn++)
768 if (fn == last_fn)
769 return false;
770
771 cp += fn->fn_name_len;
772 cpp_skip_whitespace(&cp);
773 if (*cp != '(')
774 return false;
775
776 arglen = ParseWord(par, &cp, doEval, fn->fn_name, &arg);
777 *out_token = ToToken(arglen != 0 && (!doEval || fn->fn_eval(arg)));
778
779 free(arg);
780 par->p = cp;
781 return true;
782 }
783
784 /*
785 * Parse a comparison such as '${VAR} == "value"', or a simple leaf without
786 * operator, which is a number, a variable expression or a string literal.
787 */
788 static Token
789 CondParser_ComparisonOrLeaf(CondParser *par, bool doEval)
790 {
791 Token t;
792 char *arg = NULL;
793 const char *cp;
794 const char *cp1;
795
796 /* Push anything numeric through the compare expression */
797 cp = par->p;
798 if (ch_isdigit(cp[0]) || cp[0] == '-' || cp[0] == '+')
799 return CondParser_Comparison(par, doEval);
800
801 /*
802 * Most likely we have a naked token to apply the default function to.
803 * However ".if a == b" gets here when the "a" is unquoted and doesn't
804 * start with a '$'. This surprises people.
805 * If what follows the function argument is a '=' or '!' then the
806 * syntax would be invalid if we did "defined(a)" - so instead treat
807 * as an expression.
808 */
809 /*
810 * XXX: Is it possible to have a variable expression evaluated twice
811 * at this point?
812 */
813 (void)ParseWord(par, &cp, doEval, NULL, &arg);
814 cp1 = cp;
815 cpp_skip_whitespace(&cp1);
816 if (*cp1 == '=' || *cp1 == '!' || *cp1 == '<' || *cp1 == '>')
817 return CondParser_Comparison(par, doEval);
818 par->p = cp;
819
820 /*
821 * Evaluate the argument using the default function.
822 * This path always treats .if as .ifdef. To get here, the character
823 * after .if must have been taken literally, so the argument cannot
824 * be empty - even if it contained a variable expansion.
825 */
826 t = ToToken(!doEval || EvalBare(par, arg));
827 free(arg);
828 return t;
829 }
830
831 /* Return the next token or comparison result from the parser. */
832 static Token
833 CondParser_Token(CondParser *par, bool doEval)
834 {
835 Token t;
836
837 t = par->curr;
838 if (t != TOK_NONE) {
839 par->curr = TOK_NONE;
840 return t;
841 }
842
843 cpp_skip_hspace(&par->p);
844
845 switch (par->p[0]) {
846
847 case '(':
848 par->p++;
849 return TOK_LPAREN;
850
851 case ')':
852 par->p++;
853 return TOK_RPAREN;
854
855 case '|':
856 par->p++;
857 if (par->p[0] == '|')
858 par->p++;
859 else if (opts.strict) {
860 Parse_Error(PARSE_FATAL, "Unknown operator '|'");
861 par->printedError = true;
862 return TOK_ERROR;
863 }
864 return TOK_OR;
865
866 case '&':
867 par->p++;
868 if (par->p[0] == '&')
869 par->p++;
870 else if (opts.strict) {
871 Parse_Error(PARSE_FATAL, "Unknown operator '&'");
872 par->printedError = true;
873 return TOK_ERROR;
874 }
875 return TOK_AND;
876
877 case '!':
878 par->p++;
879 return TOK_NOT;
880
881 case '#': /* XXX: see unit-tests/cond-token-plain.mk */
882 case '\n': /* XXX: why should this end the condition? */
883 /* Probably obsolete now, from 1993-03-21. */
884 case '\0':
885 return TOK_EOF;
886
887 case '"':
888 case '$':
889 return CondParser_Comparison(par, doEval);
890
891 default:
892 if (CondParser_FuncCallEmpty(par, doEval, &t))
893 return t;
894 if (CondParser_FuncCall(par, doEval, &t))
895 return t;
896 return CondParser_ComparisonOrLeaf(par, doEval);
897 }
898 }
899
900 /* Skip the next token if it equals t. */
901 static bool
902 CondParser_Skip(CondParser *par, Token t)
903 {
904 Token actual;
905
906 actual = CondParser_Token(par, false);
907 if (actual == t)
908 return true;
909
910 assert(par->curr == TOK_NONE);
911 assert(actual != TOK_NONE);
912 par->curr = actual;
913 return false;
914 }
915
916 /*
917 * Term -> '(' Or ')'
918 * Term -> '!' Term
919 * Term -> Leaf Operator Leaf
920 * Term -> Leaf
921 */
922 static CondResult
923 CondParser_Term(CondParser *par, bool doEval)
924 {
925 CondResult res;
926 Token t;
927
928 t = CondParser_Token(par, doEval);
929 if (t == TOK_TRUE)
930 return CR_TRUE;
931 if (t == TOK_FALSE)
932 return CR_FALSE;
933
934 if (t == TOK_LPAREN) {
935 res = CondParser_Or(par, doEval);
936 if (res == CR_ERROR)
937 return CR_ERROR;
938 if (CondParser_Token(par, doEval) != TOK_RPAREN)
939 return CR_ERROR;
940 return res;
941 }
942
943 if (t == TOK_NOT) {
944 res = CondParser_Term(par, doEval);
945 if (res == CR_TRUE)
946 res = CR_FALSE;
947 else if (res == CR_FALSE)
948 res = CR_TRUE;
949 return res;
950 }
951
952 return CR_ERROR;
953 }
954
955 /*
956 * And -> Term ('&&' Term)*
957 */
958 static CondResult
959 CondParser_And(CondParser *par, bool doEval)
960 {
961 CondResult res, rhs;
962
963 res = CR_TRUE;
964 do {
965 if ((rhs = CondParser_Term(par, doEval)) == CR_ERROR)
966 return CR_ERROR;
967 if (rhs == CR_FALSE) {
968 res = CR_FALSE;
969 doEval = false;
970 }
971 } while (CondParser_Skip(par, TOK_AND));
972
973 return res;
974 }
975
976 /*
977 * Or -> And ('||' And)*
978 */
979 static CondResult
980 CondParser_Or(CondParser *par, bool doEval)
981 {
982 CondResult res, rhs;
983
984 res = CR_FALSE;
985 do {
986 if ((rhs = CondParser_And(par, doEval)) == CR_ERROR)
987 return CR_ERROR;
988 if (rhs == CR_TRUE) {
989 res = CR_TRUE;
990 doEval = false;
991 }
992 } while (CondParser_Skip(par, TOK_OR));
993
994 return res;
995 }
996
997 static CondEvalResult
998 CondParser_Eval(CondParser *par, bool *out_value)
999 {
1000 CondResult res;
1001
1002 DEBUG1(COND, "CondParser_Eval: %s\n", par->p);
1003
1004 res = CondParser_Or(par, true);
1005 if (res == CR_ERROR)
1006 return COND_INVALID;
1007
1008 if (CondParser_Token(par, false) != TOK_EOF)
1009 return COND_INVALID;
1010
1011 *out_value = res == CR_TRUE;
1012 return COND_PARSE;
1013 }
1014
1015 /*
1016 * Evaluate the condition, including any side effects from the variable
1017 * expressions in the condition. The condition consists of &&, ||, !,
1018 * function(arg), comparisons and parenthetical groupings thereof.
1019 *
1020 * Results:
1021 * COND_PARSE if the condition was valid grammatically
1022 * COND_INVALID if not a valid conditional.
1023 *
1024 * *out_value is set to the boolean value of the condition
1025 */
1026 static CondEvalResult
1027 CondEvalExpression(const char *cond, bool *out_value, bool plain,
1028 bool (*evalBare)(const char *), bool negate,
1029 bool eprint, bool leftUnquotedOK)
1030 {
1031 CondParser par;
1032 CondEvalResult rval;
1033
1034 cpp_skip_hspace(&cond);
1035
1036 par.plain = plain;
1037 par.evalBare = evalBare;
1038 par.negateEvalBare = negate;
1039 par.leftUnquotedOK = leftUnquotedOK;
1040 par.p = cond;
1041 par.curr = TOK_NONE;
1042 par.printedError = false;
1043
1044 rval = CondParser_Eval(&par, out_value);
1045
1046 if (rval == COND_INVALID && eprint && !par.printedError)
1047 Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", cond);
1048
1049 return rval;
1050 }
1051
1052 /*
1053 * Evaluate a condition in a :? modifier, such as
1054 * ${"${VAR}" == value:?yes:no}.
1055 */
1056 CondEvalResult
1057 Cond_EvalCondition(const char *cond, bool *out_value)
1058 {
1059 return CondEvalExpression(cond, out_value, true,
1060 FuncDefined, false, false, true);
1061 }
1062
1063 static bool
1064 IsEndif(const char *p)
1065 {
1066 return p[0] == 'e' && p[1] == 'n' && p[2] == 'd' &&
1067 p[3] == 'i' && p[4] == 'f' && !ch_isalpha(p[5]);
1068 }
1069
1070 static bool
1071 DetermineKindOfConditional(const char **pp, bool *out_plain,
1072 bool (**out_evalBare)(const char *),
1073 bool *out_negate)
1074 {
1075 const char *p = *pp;
1076
1077 p += 2;
1078 *out_plain = false;
1079 *out_evalBare = FuncDefined;
1080 *out_negate = false;
1081 if (*p == 'n') {
1082 p++;
1083 *out_negate = true;
1084 }
1085 if (is_token(p, "def", 3)) { /* .ifdef and .ifndef */
1086 p += 3;
1087 } else if (is_token(p, "make", 4)) { /* .ifmake and .ifnmake */
1088 p += 4;
1089 *out_evalBare = FuncMake;
1090 } else if (is_token(p, "", 0) && !*out_negate) { /* plain .if */
1091 *out_plain = true;
1092 } else {
1093 /*
1094 * TODO: Add error message about unknown directive,
1095 * since there is no other known directive that starts
1096 * with 'el' or 'if'.
1097 *
1098 * Example: .elifx 123
1099 */
1100 return false;
1101 }
1102
1103 *pp = p;
1104 return true;
1105 }
1106
1107 /*
1108 * Evaluate the conditional directive in the line, which is one of:
1109 *
1110 * .if <cond>
1111 * .ifmake <cond>
1112 * .ifnmake <cond>
1113 * .ifdef <cond>
1114 * .ifndef <cond>
1115 * .elif <cond>
1116 * .elifmake <cond>
1117 * .elifnmake <cond>
1118 * .elifdef <cond>
1119 * .elifndef <cond>
1120 * .else
1121 * .endif
1122 *
1123 * In these directives, <cond> consists of &&, ||, !, function(arg),
1124 * comparisons, expressions, bare words, numbers and strings, and
1125 * parenthetical groupings thereof.
1126 *
1127 * Results:
1128 * COND_PARSE to continue parsing the lines that follow the
1129 * conditional (when <cond> evaluates to true)
1130 * COND_SKIP to skip the lines after the conditional
1131 * (when <cond> evaluates to false, or when a previous
1132 * branch has already been taken)
1133 * COND_INVALID if the conditional was not valid, either because of
1134 * a syntax error or because some variable was undefined
1135 * or because the condition could not be evaluated
1136 */
1137 CondEvalResult
1138 Cond_EvalLine(const char *line)
1139 {
1140 typedef enum IfState {
1141
1142 /* None of the previous <cond> evaluated to true. */
1143 IFS_INITIAL = 0,
1144
1145 /* The previous <cond> evaluated to true.
1146 * The lines following this condition are interpreted. */
1147 IFS_ACTIVE = 1 << 0,
1148
1149 /* The previous directive was an '.else'. */
1150 IFS_SEEN_ELSE = 1 << 1,
1151
1152 /* One of the previous <cond> evaluated to true. */
1153 IFS_WAS_ACTIVE = 1 << 2
1154
1155 } IfState;
1156
1157 static enum IfState *cond_states = NULL;
1158 static unsigned int cond_states_cap = 128;
1159
1160 bool plain;
1161 bool (*evalBare)(const char *);
1162 bool negate;
1163 bool isElif;
1164 bool value;
1165 IfState state;
1166 const char *p = line;
1167
1168 if (cond_states == NULL) {
1169 cond_states = bmake_malloc(
1170 cond_states_cap * sizeof *cond_states);
1171 cond_states[0] = IFS_ACTIVE;
1172 }
1173
1174 p++; /* skip the leading '.' */
1175 cpp_skip_hspace(&p);
1176
1177 if (IsEndif(p)) { /* It is an '.endif'. */
1178 if (p[5] != '\0') {
1179 Parse_Error(PARSE_FATAL,
1180 "The .endif directive does not take arguments");
1181 }
1182
1183 if (cond_depth == cond_min_depth) {
1184 Parse_Error(PARSE_FATAL, "if-less endif");
1185 return COND_PARSE;
1186 }
1187
1188 /* Return state for previous conditional */
1189 cond_depth--;
1190 return cond_states[cond_depth] & IFS_ACTIVE
1191 ? COND_PARSE : COND_SKIP;
1192 }
1193
1194 /* Parse the name of the directive, such as 'if', 'elif', 'endif'. */
1195 if (p[0] == 'e') {
1196 if (p[1] != 'l') {
1197 /*
1198 * Unknown directive. It might still be a
1199 * transformation rule like '.err.txt',
1200 * therefore no error message here.
1201 */
1202 return COND_INVALID;
1203 }
1204
1205 /* Quite likely this is 'else' or 'elif' */
1206 p += 2;
1207 if (is_token(p, "se", 2)) { /* It is an 'else'. */
1208
1209 if (p[2] != '\0')
1210 Parse_Error(PARSE_FATAL,
1211 "The .else directive "
1212 "does not take arguments");
1213
1214 if (cond_depth == cond_min_depth) {
1215 Parse_Error(PARSE_FATAL, "if-less else");
1216 return COND_PARSE;
1217 }
1218
1219 state = cond_states[cond_depth];
1220 if (state == IFS_INITIAL) {
1221 state = IFS_ACTIVE | IFS_SEEN_ELSE;
1222 } else {
1223 if (state & IFS_SEEN_ELSE)
1224 Parse_Error(PARSE_WARNING,
1225 "extra else");
1226 state = IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
1227 }
1228 cond_states[cond_depth] = state;
1229
1230 return state & IFS_ACTIVE ? COND_PARSE : COND_SKIP;
1231 }
1232 /* Assume for now it is an elif */
1233 isElif = true;
1234 } else
1235 isElif = false;
1236
1237 if (p[0] != 'i' || p[1] != 'f') {
1238 /*
1239 * Unknown directive. It might still be a transformation rule
1240 * like '.elisp.scm', therefore no error message here.
1241 */
1242 return COND_INVALID; /* Not an ifxxx or elifxxx line */
1243 }
1244
1245 if (!DetermineKindOfConditional(&p, &plain, &evalBare, &negate))
1246 return COND_INVALID;
1247
1248 if (isElif) {
1249 if (cond_depth == cond_min_depth) {
1250 Parse_Error(PARSE_FATAL, "if-less elif");
1251 return COND_PARSE;
1252 }
1253 state = cond_states[cond_depth];
1254 if (state & IFS_SEEN_ELSE) {
1255 Parse_Error(PARSE_WARNING, "extra elif");
1256 cond_states[cond_depth] =
1257 IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
1258 return COND_SKIP;
1259 }
1260 if (state != IFS_INITIAL) {
1261 cond_states[cond_depth] = IFS_WAS_ACTIVE;
1262 return COND_SKIP;
1263 }
1264 } else {
1265 /* Normal .if */
1266 if (cond_depth + 1 >= cond_states_cap) {
1267 /*
1268 * This is rare, but not impossible.
1269 * In meta mode, dirdeps.mk (only runs at level 0)
1270 * can need more than the default.
1271 */
1272 cond_states_cap += 32;
1273 cond_states = bmake_realloc(cond_states,
1274 cond_states_cap *
1275 sizeof *cond_states);
1276 }
1277 state = cond_states[cond_depth];
1278 cond_depth++;
1279 if (!(state & IFS_ACTIVE)) {
1280 /*
1281 * If we aren't parsing the data,
1282 * treat as always false.
1283 */
1284 cond_states[cond_depth] = IFS_WAS_ACTIVE;
1285 return COND_SKIP;
1286 }
1287 }
1288
1289 /* And evaluate the conditional expression */
1290 if (CondEvalExpression(p, &value, plain, evalBare, negate,
1291 true, false) == COND_INVALID) {
1292 /* Syntax error in conditional, error message already output. */
1293 /* Skip everything to matching .endif */
1294 /* XXX: An extra '.else' is not detected in this case. */
1295 cond_states[cond_depth] = IFS_WAS_ACTIVE;
1296 return COND_SKIP;
1297 }
1298
1299 if (!value) {
1300 cond_states[cond_depth] = IFS_INITIAL;
1301 return COND_SKIP;
1302 }
1303 cond_states[cond_depth] = IFS_ACTIVE;
1304 return COND_PARSE;
1305 }
1306
1307 void
1308 Cond_restore_depth(unsigned int saved_depth)
1309 {
1310 unsigned int open_conds = cond_depth - cond_min_depth;
1311
1312 if (open_conds != 0 || saved_depth > cond_depth) {
1313 Parse_Error(PARSE_FATAL, "%u open conditional%s",
1314 open_conds, open_conds == 1 ? "" : "s");
1315 cond_depth = cond_min_depth;
1316 }
1317
1318 cond_min_depth = saved_depth;
1319 }
1320
1321 unsigned int
1322 Cond_save_depth(void)
1323 {
1324 unsigned int depth = cond_min_depth;
1325
1326 cond_min_depth = cond_depth;
1327 return depth;
1328 }
1329