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