cond.c revision 1.305 1 /* $NetBSD: cond.c,v 1.305 2021/12/15 12:24:13 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.305 2021/12/15 12:24:13 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 buf.data = NULL;
527 cleanup:
528 Buf_Done(&buf);
529 *out_str = str;
530 }
531
532 static bool
533 EvalBare(const CondParser *par, const char *arg)
534 {
535 bool res = par->evalBare(arg);
536 return par->negateEvalBare ? !res : res;
537 }
538
539 /*
540 * Evaluate a "comparison without operator", such as in ".if ${VAR}" or
541 * ".if 0".
542 */
543 static bool
544 EvalNotEmpty(CondParser *par, const char *value, bool quoted)
545 {
546 double num;
547
548 /* For .ifxxx "...", check for non-empty string. */
549 if (quoted)
550 return value[0] != '\0';
551
552 /* For .ifxxx <number>, compare against zero */
553 if (TryParseNumber(value, &num))
554 return num != 0.0;
555
556 /* For .if ${...}, check for non-empty string. This is different from
557 * the evaluation function from that .if variant, which would test
558 * whether a variable of the given name were defined. */
559 /*
560 * XXX: Whitespace should count as empty, just as in
561 * CondParser_FuncCallEmpty.
562 */
563 if (par->plain)
564 return value[0] != '\0';
565
566 return EvalBare(par, value);
567 }
568
569 /* Evaluate a numerical comparison, such as in ".if ${VAR} >= 9". */
570 static bool
571 EvalCompareNum(double lhs, ComparisonOp op, double rhs)
572 {
573 DEBUG3(COND, "lhs = %f, rhs = %f, op = %.2s\n", lhs, rhs, opname[op]);
574
575 switch (op) {
576 case LT:
577 return lhs < rhs;
578 case LE:
579 return lhs <= rhs;
580 case GT:
581 return lhs > rhs;
582 case GE:
583 return lhs >= rhs;
584 case NE:
585 return lhs != rhs;
586 default:
587 return lhs == rhs;
588 }
589 }
590
591 static Token
592 EvalCompareStr(CondParser *par, const char *lhs,
593 ComparisonOp op, const char *rhs)
594 {
595 if (op != EQ && op != NE) {
596 Parse_Error(PARSE_FATAL,
597 "String comparison operator must be either == or !=");
598 par->printedError = true;
599 return TOK_ERROR;
600 }
601
602 DEBUG3(COND, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
603 lhs, rhs, opname[op]);
604 return ToToken((op == EQ) == (strcmp(lhs, rhs) == 0));
605 }
606
607 /* Evaluate a comparison, such as "${VAR} == 12345". */
608 static Token
609 EvalCompare(CondParser *par, const char *lhs, bool lhsQuoted,
610 ComparisonOp op, const char *rhs, bool rhsQuoted)
611 {
612 double left, right;
613
614 if (!rhsQuoted && !lhsQuoted)
615 if (TryParseNumber(lhs, &left) && TryParseNumber(rhs, &right))
616 return ToToken(EvalCompareNum(left, op, right));
617
618 return EvalCompareStr(par, lhs, op, rhs);
619 }
620
621 static bool
622 CondParser_ComparisonOp(CondParser *par, ComparisonOp *out_op)
623 {
624 const char *p = par->p;
625
626 if (p[0] == '<' && p[1] == '=')
627 return par->p += 2, *out_op = LE, true;
628 if (p[0] == '<')
629 return par->p += 1, *out_op = LT, true;
630 if (p[0] == '>' && p[1] == '=')
631 return par->p += 2, *out_op = GE, true;
632 if (p[0] == '>')
633 return par->p += 1, *out_op = GT, true;
634 if (p[0] == '=' && p[1] == '=')
635 return par->p += 2, *out_op = EQ, true;
636 if (p[0] == '!' && p[1] == '=')
637 return par->p += 2, *out_op = NE, true;
638 return false;
639 }
640
641 /*
642 * Parse a comparison condition such as:
643 *
644 * 0
645 * ${VAR:Mpattern}
646 * ${VAR} == value
647 * ${VAR:U0} < 12345
648 */
649 static Token
650 CondParser_Comparison(CondParser *par, bool doEval)
651 {
652 Token t = TOK_ERROR;
653 FStr lhs, rhs;
654 ComparisonOp op;
655 bool lhsQuoted, rhsQuoted;
656
657 CondParser_Leaf(par, doEval, par->leftUnquotedOK, &lhs, &lhsQuoted);
658 if (lhs.str == NULL)
659 goto done_lhs;
660
661 CondParser_SkipWhitespace(par);
662
663 if (!CondParser_ComparisonOp(par, &op)) {
664 /* Unknown operator, compare against an empty string or 0. */
665 t = ToToken(doEval && EvalNotEmpty(par, lhs.str, lhsQuoted));
666 goto done_lhs;
667 }
668
669 CondParser_SkipWhitespace(par);
670
671 if (par->p[0] == '\0') {
672 Parse_Error(PARSE_FATAL,
673 "Missing right-hand side of operator '%s'", opname[op]);
674 par->printedError = true;
675 goto done_lhs;
676 }
677
678 CondParser_Leaf(par, doEval, true, &rhs, &rhsQuoted);
679 if (rhs.str == NULL)
680 goto done_rhs;
681
682 if (!doEval) {
683 t = TOK_FALSE;
684 goto done_rhs;
685 }
686
687 t = EvalCompare(par, lhs.str, lhsQuoted, op, rhs.str, rhsQuoted);
688
689 done_rhs:
690 FStr_Done(&rhs);
691 done_lhs:
692 FStr_Done(&lhs);
693 return t;
694 }
695
696 /*
697 * The argument to empty() is a variable name, optionally followed by
698 * variable modifiers.
699 */
700 static bool
701 CondParser_FuncCallEmpty(CondParser *par, bool doEval, Token *out_token)
702 {
703 const char *cp = par->p;
704 Token tok;
705 FStr val;
706
707 if (!is_token(cp, "empty", 5))
708 return false;
709 cp += 5;
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 = val.str[0] != '\0' && doEval ? TOK_FALSE : TOK_TRUE;
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 static const struct fn_def {
738 const char fn_name[9];
739 unsigned char fn_name_len;
740 bool (*fn_eval)(const char *);
741 } fns[] = {
742 { "defined", 7, FuncDefined },
743 { "make", 4, FuncMake },
744 { "exists", 6, FuncExists },
745 { "target", 6, FuncTarget },
746 { "commands", 8, FuncCommands }
747 };
748 const struct fn_def *fn;
749 char *arg = NULL;
750 size_t arglen;
751 const char *cp = par->p;
752 const struct fn_def *last_fn = fns + sizeof fns / sizeof fns[0] - 1;
753
754 for (fn = fns; !is_token(cp, fn->fn_name, fn->fn_name_len); fn++)
755 if (fn == last_fn)
756 return false;
757
758 cp += fn->fn_name_len;
759 cpp_skip_whitespace(&cp);
760 if (*cp != '(')
761 return false;
762
763 arglen = ParseWord(par, &cp, doEval, fn->fn_name, &arg);
764 *out_token = ToToken(arglen != 0 && (!doEval || fn->fn_eval(arg)));
765
766 free(arg);
767 par->p = cp;
768 return true;
769 }
770
771 /*
772 * Parse a comparison that neither starts with '"' nor '$', such as the
773 * unusual 'bare == right' or '3 == ${VAR}', or a simple leaf without
774 * operator, which is a number, a variable expression or a string literal.
775 *
776 * TODO: Can this be merged into CondParser_Comparison?
777 */
778 static Token
779 CondParser_ComparisonOrLeaf(CondParser *par, bool doEval)
780 {
781 Token t;
782 char *arg = NULL;
783 const char *cp;
784 const char *cp1;
785
786 /* Push anything numeric through the compare expression */
787 cp = par->p;
788 if (ch_isdigit(cp[0]) || cp[0] == '-' || cp[0] == '+')
789 return CondParser_Comparison(par, doEval);
790
791 /*
792 * Most likely we have a naked token to apply the default function to.
793 * However ".if a == b" gets here when the "a" is unquoted and doesn't
794 * start with a '$'. This surprises people.
795 * If what follows the function argument is a '=' or '!' then the
796 * syntax would be invalid if we did "defined(a)" - so instead treat
797 * as an expression.
798 */
799 /*
800 * XXX: Is it possible to have a variable expression evaluated twice
801 * at this point?
802 */
803 (void)ParseWord(par, &cp, doEval, NULL, &arg);
804 cp1 = cp;
805 cpp_skip_whitespace(&cp1);
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 CondEvalResult
988 CondParser_Eval(CondParser *par, bool *out_value)
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)
996 return COND_INVALID;
997
998 if (CondParser_Token(par, false) != TOK_EOF)
999 return COND_INVALID;
1000
1001 *out_value = res == CR_TRUE;
1002 return COND_PARSE;
1003 }
1004
1005 /*
1006 * Evaluate the condition, including any side effects from the variable
1007 * expressions in the condition. The condition consists of &&, ||, !,
1008 * function(arg), comparisons and parenthetical groupings thereof.
1009 *
1010 * Results:
1011 * COND_PARSE if the condition was valid grammatically
1012 * COND_INVALID if not a valid conditional.
1013 *
1014 * *out_value is set to the boolean value of the condition
1015 */
1016 static CondEvalResult
1017 CondEvalExpression(const char *cond, bool *out_value, bool plain,
1018 bool (*evalBare)(const char *), bool negate,
1019 bool eprint, bool leftUnquotedOK)
1020 {
1021 CondParser par;
1022 CondEvalResult rval;
1023
1024 cpp_skip_hspace(&cond);
1025
1026 par.plain = plain;
1027 par.evalBare = evalBare;
1028 par.negateEvalBare = negate;
1029 par.leftUnquotedOK = leftUnquotedOK;
1030 par.p = cond;
1031 par.curr = TOK_NONE;
1032 par.printedError = false;
1033
1034 rval = CondParser_Eval(&par, out_value);
1035
1036 if (rval == COND_INVALID && eprint && !par.printedError)
1037 Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", cond);
1038
1039 return rval;
1040 }
1041
1042 /*
1043 * Evaluate a condition in a :? modifier, such as
1044 * ${"${VAR}" == value:?yes:no}.
1045 */
1046 CondEvalResult
1047 Cond_EvalCondition(const char *cond, bool *out_value)
1048 {
1049 return CondEvalExpression(cond, out_value, true,
1050 FuncDefined, false, false, true);
1051 }
1052
1053 static bool
1054 IsEndif(const char *p)
1055 {
1056 return p[0] == 'e' && p[1] == 'n' && p[2] == 'd' &&
1057 p[3] == 'i' && p[4] == 'f' && !ch_isalpha(p[5]);
1058 }
1059
1060 static bool
1061 DetermineKindOfConditional(const char **pp, bool *out_plain,
1062 bool (**out_evalBare)(const char *),
1063 bool *out_negate)
1064 {
1065 const char *p = *pp;
1066
1067 p += 2;
1068 *out_plain = false;
1069 *out_evalBare = FuncDefined;
1070 *out_negate = false;
1071 if (*p == 'n') {
1072 p++;
1073 *out_negate = true;
1074 }
1075 if (is_token(p, "def", 3)) { /* .ifdef and .ifndef */
1076 p += 3;
1077 } else if (is_token(p, "make", 4)) { /* .ifmake and .ifnmake */
1078 p += 4;
1079 *out_evalBare = FuncMake;
1080 } else if (is_token(p, "", 0) && !*out_negate) { /* plain .if */
1081 *out_plain = true;
1082 } else {
1083 /*
1084 * TODO: Add error message about unknown directive,
1085 * since there is no other known directive that starts
1086 * with 'el' or 'if'.
1087 *
1088 * Example: .elifx 123
1089 */
1090 return false;
1091 }
1092
1093 *pp = p;
1094 return true;
1095 }
1096
1097 /*
1098 * Evaluate the conditional directive in the line, which is one of:
1099 *
1100 * .if <cond>
1101 * .ifmake <cond>
1102 * .ifnmake <cond>
1103 * .ifdef <cond>
1104 * .ifndef <cond>
1105 * .elif <cond>
1106 * .elifmake <cond>
1107 * .elifnmake <cond>
1108 * .elifdef <cond>
1109 * .elifndef <cond>
1110 * .else
1111 * .endif
1112 *
1113 * In these directives, <cond> consists of &&, ||, !, function(arg),
1114 * comparisons, expressions, bare words, numbers and strings, and
1115 * parenthetical groupings thereof.
1116 *
1117 * Results:
1118 * COND_PARSE to continue parsing the lines that follow the
1119 * conditional (when <cond> evaluates to true)
1120 * COND_SKIP to skip the lines after the conditional
1121 * (when <cond> evaluates to false, or when a previous
1122 * branch has already been taken)
1123 * COND_INVALID if the conditional was not valid, either because of
1124 * a syntax error or because some variable was undefined
1125 * or because the condition could not be evaluated
1126 */
1127 CondEvalResult
1128 Cond_EvalLine(const char *line)
1129 {
1130 typedef enum IfState {
1131
1132 /* None of the previous <cond> evaluated to true. */
1133 IFS_INITIAL = 0,
1134
1135 /* The previous <cond> evaluated to true.
1136 * The lines following this condition are interpreted. */
1137 IFS_ACTIVE = 1 << 0,
1138
1139 /* The previous directive was an '.else'. */
1140 IFS_SEEN_ELSE = 1 << 1,
1141
1142 /* One of the previous <cond> evaluated to true. */
1143 IFS_WAS_ACTIVE = 1 << 2
1144
1145 } IfState;
1146
1147 static enum IfState *cond_states = NULL;
1148 static unsigned int cond_states_cap = 128;
1149
1150 bool plain;
1151 bool (*evalBare)(const char *);
1152 bool negate;
1153 bool isElif;
1154 bool value;
1155 IfState state;
1156 const char *p = line;
1157
1158 if (cond_states == NULL) {
1159 cond_states = bmake_malloc(
1160 cond_states_cap * sizeof *cond_states);
1161 cond_states[0] = IFS_ACTIVE;
1162 }
1163
1164 p++; /* skip the leading '.' */
1165 cpp_skip_hspace(&p);
1166
1167 if (IsEndif(p)) { /* It is an '.endif'. */
1168 if (p[5] != '\0') {
1169 Parse_Error(PARSE_FATAL,
1170 "The .endif directive does not take arguments");
1171 }
1172
1173 if (cond_depth == cond_min_depth) {
1174 Parse_Error(PARSE_FATAL, "if-less endif");
1175 return COND_PARSE;
1176 }
1177
1178 /* Return state for previous conditional */
1179 cond_depth--;
1180 return cond_states[cond_depth] & IFS_ACTIVE
1181 ? COND_PARSE : COND_SKIP;
1182 }
1183
1184 /* Parse the name of the directive, such as 'if', 'elif', 'endif'. */
1185 if (p[0] == 'e') {
1186 if (p[1] != 'l') {
1187 /*
1188 * Unknown directive. It might still be a
1189 * transformation rule like '.err.txt',
1190 * therefore no error message here.
1191 */
1192 return COND_INVALID;
1193 }
1194
1195 /* Quite likely this is 'else' or 'elif' */
1196 p += 2;
1197 if (is_token(p, "se", 2)) { /* It is an 'else'. */
1198
1199 if (p[2] != '\0')
1200 Parse_Error(PARSE_FATAL,
1201 "The .else directive "
1202 "does not take arguments");
1203
1204 if (cond_depth == cond_min_depth) {
1205 Parse_Error(PARSE_FATAL, "if-less else");
1206 return COND_PARSE;
1207 }
1208
1209 state = cond_states[cond_depth];
1210 if (state == IFS_INITIAL) {
1211 state = IFS_ACTIVE | IFS_SEEN_ELSE;
1212 } else {
1213 if (state & IFS_SEEN_ELSE)
1214 Parse_Error(PARSE_WARNING,
1215 "extra else");
1216 state = IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
1217 }
1218 cond_states[cond_depth] = state;
1219
1220 return state & IFS_ACTIVE ? COND_PARSE : COND_SKIP;
1221 }
1222 /* Assume for now it is an elif */
1223 isElif = true;
1224 } else
1225 isElif = false;
1226
1227 if (p[0] != 'i' || p[1] != 'f') {
1228 /*
1229 * Unknown directive. It might still be a transformation rule
1230 * like '.elisp.scm', therefore no error message here.
1231 */
1232 return COND_INVALID; /* Not an ifxxx or elifxxx line */
1233 }
1234
1235 if (!DetermineKindOfConditional(&p, &plain, &evalBare, &negate))
1236 return COND_INVALID;
1237
1238 if (isElif) {
1239 if (cond_depth == cond_min_depth) {
1240 Parse_Error(PARSE_FATAL, "if-less elif");
1241 return COND_PARSE;
1242 }
1243 state = cond_states[cond_depth];
1244 if (state & IFS_SEEN_ELSE) {
1245 Parse_Error(PARSE_WARNING, "extra elif");
1246 cond_states[cond_depth] =
1247 IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
1248 return COND_SKIP;
1249 }
1250 if (state != IFS_INITIAL) {
1251 cond_states[cond_depth] = IFS_WAS_ACTIVE;
1252 return COND_SKIP;
1253 }
1254 } else {
1255 /* Normal .if */
1256 if (cond_depth + 1 >= cond_states_cap) {
1257 /*
1258 * This is rare, but not impossible.
1259 * In meta mode, dirdeps.mk (only runs at level 0)
1260 * can need more than the default.
1261 */
1262 cond_states_cap += 32;
1263 cond_states = bmake_realloc(cond_states,
1264 cond_states_cap * sizeof *cond_states);
1265 }
1266 state = cond_states[cond_depth];
1267 cond_depth++;
1268 if (!(state & IFS_ACTIVE)) {
1269 /*
1270 * If we aren't parsing the data,
1271 * treat as always false.
1272 */
1273 cond_states[cond_depth] = IFS_WAS_ACTIVE;
1274 return COND_SKIP;
1275 }
1276 }
1277
1278 /* And evaluate the conditional expression */
1279 if (CondEvalExpression(p, &value, plain, evalBare, negate,
1280 true, false) == COND_INVALID) {
1281 /* Syntax error in conditional, error message already output. */
1282 /* Skip everything to matching .endif */
1283 /* XXX: An extra '.else' is not detected in this case. */
1284 cond_states[cond_depth] = IFS_WAS_ACTIVE;
1285 return COND_SKIP;
1286 }
1287
1288 if (!value) {
1289 cond_states[cond_depth] = IFS_INITIAL;
1290 return COND_SKIP;
1291 }
1292 cond_states[cond_depth] = IFS_ACTIVE;
1293 return COND_PARSE;
1294 }
1295
1296 void
1297 Cond_restore_depth(unsigned int saved_depth)
1298 {
1299 unsigned int open_conds = cond_depth - cond_min_depth;
1300
1301 if (open_conds != 0 || saved_depth > cond_depth) {
1302 Parse_Error(PARSE_FATAL, "%u open conditional%s",
1303 open_conds, open_conds == 1 ? "" : "s");
1304 cond_depth = cond_min_depth;
1305 }
1306
1307 cond_min_depth = saved_depth;
1308 }
1309
1310 unsigned int
1311 Cond_save_depth(void)
1312 {
1313 unsigned int depth = cond_min_depth;
1314
1315 cond_min_depth = cond_depth;
1316 return depth;
1317 }
1318