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