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