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