cond.c revision 1.271 1 /* $NetBSD: cond.c,v 1.271 2021/09/21 20:51:38 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.271 2021/09/21 20:51:38 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 const doEval, bool const quoted,
417 Buffer *buf, FStr *const inout_str)
418 {
419 VarEvalMode emode;
420 const char *nested_p;
421 bool atStart;
422 VarParseResult parseResult;
423
424 /* if we are in quotes, an undefined variable is ok */
425 emode = doEval && !quoted ? VARE_UNDEFERR
426 : doEval ? VARE_WANTRES
427 : VARE_PARSE_ONLY;
428
429 nested_p = par->p;
430 atStart = nested_p == start;
431 parseResult = Var_Parse(&nested_p, SCOPE_CMDLINE, emode, inout_str);
432 /* TODO: handle errors */
433 if (inout_str->str == var_Error) {
434 if (parseResult == VPR_ERR) {
435 /*
436 * FIXME: Even if an error occurs, there is no
437 * guarantee that it is reported.
438 *
439 * See cond-token-plain.mk $$$$$$$$.
440 */
441 par->printedError = true;
442 }
443 /*
444 * XXX: Can there be any situation in which a returned
445 * var_Error needs to be freed?
446 */
447 FStr_Done(inout_str);
448 /*
449 * Even if !doEval, we still report syntax errors, which is
450 * what getting var_Error back with !doEval means.
451 */
452 *inout_str = FStr_InitRefer(NULL);
453 return false;
454 }
455 par->p = nested_p;
456
457 /*
458 * If the '$' started the string literal (which means no quotes), and
459 * the variable expression is followed by a space, looks like a
460 * comparison operator or is the end of the expression, we are done.
461 */
462 if (atStart && is_separator(par->p[0]))
463 return false;
464
465 Buf_AddStr(buf, inout_str->str);
466 FStr_Done(inout_str);
467 *inout_str = FStr_InitRefer(NULL); /* not finished yet */
468 return true;
469 }
470
471 /*
472 * Parse a string from a variable expression or an optionally quoted
473 * string. This is called for the left-hand and right-hand sides of
474 * comparisons.
475 *
476 * Results:
477 * Returns the string, absent any quotes, or NULL on error.
478 * Sets out_quoted if the leaf was a quoted string literal.
479 */
480 static void
481 CondParser_Leaf(CondParser *par, bool doEval, bool strictLHS,
482 FStr *out_str, bool *out_quoted)
483 {
484 Buffer buf;
485 FStr str;
486 bool quoted;
487 const char *start;
488
489 Buf_Init(&buf);
490 str = FStr_InitRefer(NULL);
491 *out_quoted = quoted = par->p[0] == '"';
492 start = par->p;
493 if (quoted)
494 par->p++;
495
496 while (par->p[0] != '\0' && str.str == NULL) {
497 switch (par->p[0]) {
498 case '\\':
499 par->p++;
500 if (par->p[0] != '\0') {
501 Buf_AddByte(&buf, par->p[0]);
502 par->p++;
503 }
504 continue;
505 case '"':
506 par->p++;
507 if (quoted)
508 goto got_str; /* skip the closing quote */
509 Buf_AddByte(&buf, '"');
510 continue;
511 case ')': /* see is_separator */
512 case '!':
513 case '=':
514 case '>':
515 case '<':
516 case ' ':
517 case '\t':
518 if (!quoted)
519 goto got_str;
520 Buf_AddByte(&buf, par->p[0]);
521 par->p++;
522 continue;
523 case '$':
524 if (!CondParser_StringExpr(par,
525 start, doEval, quoted, &buf, &str))
526 goto cleanup;
527 continue;
528 default:
529 if (strictLHS && !quoted && *start != '$' &&
530 !ch_isdigit(*start)) {
531 /*
532 * The left-hand side must be quoted,
533 * a variable reference or a number.
534 */
535 str = FStr_InitRefer(NULL);
536 goto cleanup;
537 }
538 Buf_AddByte(&buf, par->p[0]);
539 par->p++;
540 continue;
541 }
542 }
543 got_str:
544 str = FStr_InitOwn(buf.data);
545 cleanup:
546 Buf_DoneData(&buf); /* XXX: memory leak on failure? */
547 *out_str = str;
548 }
549
550 static bool
551 EvalBare(const CondParser *par, const char *arg, size_t arglen)
552 {
553 bool res = par->evalBare(arglen, arg);
554 return par->negateEvalBare ? !res : res;
555 }
556
557 /*
558 * Evaluate a "comparison without operator", such as in ".if ${VAR}" or
559 * ".if 0".
560 */
561 static bool
562 EvalNotEmpty(CondParser *par, const char *value, bool quoted)
563 {
564 double num;
565
566 /* For .ifxxx "...", check for non-empty string. */
567 if (quoted)
568 return value[0] != '\0';
569
570 /* For .ifxxx <number>, compare against zero */
571 if (TryParseNumber(value, &num))
572 return num != 0.0;
573
574 /* For .if ${...}, check for non-empty string. This is different from
575 * the evaluation function from that .if variant, which would test
576 * whether a variable of the given name were defined. */
577 /* XXX: Whitespace should count as empty, just as in ParseEmptyArg. */
578 if (par->plain)
579 return value[0] != '\0';
580
581 return EvalBare(par, value, strlen(value));
582 }
583
584 /* Evaluate a numerical comparison, such as in ".if ${VAR} >= 9". */
585 static bool
586 EvalCompareNum(double lhs, ComparisonOp op, double rhs)
587 {
588 DEBUG3(COND, "lhs = %f, rhs = %f, op = %.2s\n", lhs, rhs, opname[op]);
589
590 switch (op) {
591 case LT:
592 return lhs < rhs;
593 case LE:
594 return lhs <= rhs;
595 case GT:
596 return lhs > rhs;
597 case GE:
598 return lhs >= rhs;
599 case NE:
600 return lhs != rhs;
601 default:
602 return lhs == rhs;
603 }
604 }
605
606 static Token
607 EvalCompareStr(CondParser *par, const char *lhs,
608 ComparisonOp op, const char *rhs)
609 {
610 if (op != EQ && op != NE) {
611 Parse_Error(PARSE_FATAL,
612 "String comparison operator must be either == or !=");
613 par->printedError = true;
614 return TOK_ERROR;
615 }
616
617 DEBUG3(COND, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
618 lhs, rhs, opname[op]);
619 return ToToken((op == EQ) == (strcmp(lhs, rhs) == 0));
620 }
621
622 /* Evaluate a comparison, such as "${VAR} == 12345". */
623 static Token
624 EvalCompare(CondParser *par, const char *lhs, bool lhsQuoted,
625 ComparisonOp op, const char *rhs, bool rhsQuoted)
626 {
627 double left, right;
628
629 if (!rhsQuoted && !lhsQuoted)
630 if (TryParseNumber(lhs, &left) && TryParseNumber(rhs, &right))
631 return ToToken(EvalCompareNum(left, op, right));
632
633 return EvalCompareStr(par, lhs, op, rhs);
634 }
635
636 static bool
637 CondParser_ComparisonOp(CondParser *par, ComparisonOp *out_op)
638 {
639 const char *p = par->p;
640
641 if (p[0] == '<' && p[1] == '=') {
642 *out_op = LE;
643 goto length_2;
644 } else if (p[0] == '<') {
645 *out_op = LT;
646 goto length_1;
647 } else if (p[0] == '>' && p[1] == '=') {
648 *out_op = GE;
649 goto length_2;
650 } else if (p[0] == '>') {
651 *out_op = GT;
652 goto length_1;
653 } else if (p[0] == '=' && p[1] == '=') {
654 *out_op = EQ;
655 goto length_2;
656 } else if (p[0] == '!' && p[1] == '=') {
657 *out_op = NE;
658 goto length_2;
659 }
660 return false;
661
662 length_2:
663 par->p = p + 2;
664 return true;
665 length_1:
666 par->p = p + 1;
667 return true;
668 }
669
670 /*
671 * Parse a comparison condition such as:
672 *
673 * 0
674 * ${VAR:Mpattern}
675 * ${VAR} == value
676 * ${VAR:U0} < 12345
677 */
678 static Token
679 CondParser_Comparison(CondParser *par, bool doEval)
680 {
681 Token t = TOK_ERROR;
682 FStr lhs, rhs;
683 ComparisonOp op;
684 bool lhsQuoted, rhsQuoted;
685
686 CondParser_Leaf(par, doEval, lhsStrict, &lhs, &lhsQuoted);
687 if (lhs.str == NULL)
688 goto done_lhs;
689
690 CondParser_SkipWhitespace(par);
691
692 if (!CondParser_ComparisonOp(par, &op)) {
693 /* Unknown operator, compare against an empty string or 0. */
694 t = ToToken(doEval && EvalNotEmpty(par, lhs.str, lhsQuoted));
695 goto done_lhs;
696 }
697
698 CondParser_SkipWhitespace(par);
699
700 if (par->p[0] == '\0') {
701 Parse_Error(PARSE_FATAL,
702 "Missing right-hand side of operator '%s'", opname[op]);
703 par->printedError = true;
704 goto done_lhs;
705 }
706
707 CondParser_Leaf(par, doEval, false, &rhs, &rhsQuoted);
708 if (rhs.str == NULL)
709 goto done_rhs;
710
711 if (!doEval) {
712 t = TOK_FALSE;
713 goto done_rhs;
714 }
715
716 t = EvalCompare(par, lhs.str, lhsQuoted, op, rhs.str, rhsQuoted);
717
718 done_rhs:
719 FStr_Done(&rhs);
720 done_lhs:
721 FStr_Done(&lhs);
722 return t;
723 }
724
725 /*
726 * The argument to empty() is a variable name, optionally followed by
727 * variable modifiers.
728 */
729 /*ARGSUSED*/
730 static size_t
731 ParseEmptyArg(CondParser *par MAKE_ATTR_UNUSED, const char **pp,
732 bool doEval, const char *func MAKE_ATTR_UNUSED,
733 char **out_arg)
734 {
735 FStr val;
736 size_t magic_res;
737
738 /* We do all the work here and return the result as the length */
739 *out_arg = NULL;
740
741 (*pp)--; /* Make (*pp)[1] point to the '('. */
742 (void)Var_Parse(pp, SCOPE_CMDLINE,
743 doEval ? VARE_WANTRES : VARE_PARSE_ONLY, &val);
744 /* TODO: handle errors */
745 /* If successful, *pp points beyond the closing ')' now. */
746
747 if (val.str == var_Error) {
748 FStr_Done(&val);
749 return (size_t)-1;
750 }
751
752 /*
753 * A variable is empty when it just contains spaces...
754 * 4/15/92, christos
755 */
756 cpp_skip_whitespace(&val.str);
757
758 /*
759 * For consistency with the other functions we can't generate the
760 * true/false here.
761 */
762 magic_res = val.str[0] != '\0' ? 2 : 1;
763 FStr_Done(&val);
764 return magic_res;
765 }
766
767 /*ARGSUSED*/
768 static bool
769 FuncEmpty(size_t arglen, const char *arg MAKE_ATTR_UNUSED)
770 {
771 /* Magic values ahead, see ParseEmptyArg. */
772 return arglen == 1;
773 }
774
775 /* Parse a function call expression, such as 'defined(${file})'. */
776 static bool
777 CondParser_FuncCall(CondParser *par, bool doEval, Token *out_token)
778 {
779 static const struct fn_def {
780 const char *fn_name;
781 size_t fn_name_len;
782 size_t (*fn_parse)(CondParser *, const char **, bool,
783 const char *, char **);
784 bool (*fn_eval)(size_t, const char *);
785 } fns[] = {
786 { "defined", 7, ParseFuncArg, FuncDefined },
787 { "make", 4, ParseFuncArg, FuncMake },
788 { "exists", 6, ParseFuncArg, FuncExists },
789 { "empty", 5, ParseEmptyArg, FuncEmpty },
790 { "target", 6, ParseFuncArg, FuncTarget },
791 { "commands", 8, ParseFuncArg, FuncCommands }
792 };
793 const struct fn_def *fn;
794 char *arg = NULL;
795 size_t arglen;
796 const char *cp = par->p;
797 const struct fn_def *fns_end = fns + sizeof fns / sizeof fns[0];
798
799 for (fn = fns; fn != fns_end; fn++) {
800 if (!is_token(cp, fn->fn_name, fn->fn_name_len))
801 continue;
802
803 cp += fn->fn_name_len;
804 cpp_skip_whitespace(&cp);
805 if (*cp != '(')
806 break;
807
808 arglen = fn->fn_parse(par, &cp, doEval, fn->fn_name, &arg);
809 if (arglen == 0 || arglen == (size_t)-1) {
810 par->p = cp;
811 *out_token = arglen == 0 ? TOK_FALSE : TOK_ERROR;
812 return true;
813 }
814
815 /* Evaluate the argument using the required function. */
816 *out_token = ToToken(!doEval || fn->fn_eval(arglen, arg));
817 free(arg);
818 par->p = cp;
819 return true;
820 }
821
822 return false;
823 }
824
825 /*
826 * Parse a comparison such as '${VAR} == "value"', or a simple leaf without
827 * operator, which is a number, a variable expression or a string literal.
828 */
829 static Token
830 CondParser_ComparisonOrLeaf(CondParser *par, bool doEval)
831 {
832 Token t;
833 char *arg = NULL;
834 size_t arglen;
835 const char *cp;
836 const char *cp1;
837
838 /* Push anything numeric through the compare expression */
839 cp = par->p;
840 if (ch_isdigit(cp[0]) || cp[0] == '-' || cp[0] == '+')
841 return CondParser_Comparison(par, doEval);
842
843 /*
844 * Most likely we have a naked token to apply the default function to.
845 * However ".if a == b" gets here when the "a" is unquoted and doesn't
846 * start with a '$'. This surprises people.
847 * If what follows the function argument is a '=' or '!' then the
848 * syntax would be invalid if we did "defined(a)" - so instead treat
849 * as an expression.
850 */
851 /*
852 * XXX: Is it possible to have a variable expression evaluated twice
853 * at this point?
854 */
855 arglen = ParseFuncArg(par, &cp, doEval, NULL, &arg);
856 cp1 = cp;
857 cpp_skip_whitespace(&cp1);
858 if (*cp1 == '=' || *cp1 == '!' || *cp1 == '<' || *cp1 == '>')
859 return CondParser_Comparison(par, doEval);
860 par->p = cp;
861
862 /*
863 * Evaluate the argument using the default function.
864 * This path always treats .if as .ifdef. To get here, the character
865 * after .if must have been taken literally, so the argument cannot
866 * be empty - even if it contained a variable expansion.
867 */
868 t = ToToken(!doEval || EvalBare(par, arg, arglen));
869 free(arg);
870 return t;
871 }
872
873 /* Return the next token or comparison result from the parser. */
874 static Token
875 CondParser_Token(CondParser *par, bool doEval)
876 {
877 Token t;
878
879 t = par->curr;
880 if (t != TOK_NONE) {
881 par->curr = TOK_NONE;
882 return t;
883 }
884
885 cpp_skip_hspace(&par->p);
886
887 switch (par->p[0]) {
888
889 case '(':
890 par->p++;
891 return TOK_LPAREN;
892
893 case ')':
894 par->p++;
895 return TOK_RPAREN;
896
897 case '|':
898 par->p++;
899 if (par->p[0] == '|')
900 par->p++;
901 else if (opts.strict) {
902 Parse_Error(PARSE_FATAL, "Unknown operator '|'");
903 par->printedError = true;
904 return TOK_ERROR;
905 }
906 return TOK_OR;
907
908 case '&':
909 par->p++;
910 if (par->p[0] == '&')
911 par->p++;
912 else if (opts.strict) {
913 Parse_Error(PARSE_FATAL, "Unknown operator '&'");
914 par->printedError = true;
915 return TOK_ERROR;
916 }
917 return TOK_AND;
918
919 case '!':
920 par->p++;
921 return TOK_NOT;
922
923 case '#': /* XXX: see unit-tests/cond-token-plain.mk */
924 case '\n': /* XXX: why should this end the condition? */
925 /* Probably obsolete now, from 1993-03-21. */
926 case '\0':
927 return TOK_EOF;
928
929 case '"':
930 case '$':
931 return CondParser_Comparison(par, doEval);
932
933 default:
934 if (CondParser_FuncCall(par, doEval, &t))
935 return t;
936 return CondParser_ComparisonOrLeaf(par, doEval);
937 }
938 }
939
940 /*
941 * Term -> '(' Or ')'
942 * Term -> '!' Term
943 * Term -> Leaf Operator Leaf
944 * Term -> Leaf
945 */
946 static CondResult
947 CondParser_Term(CondParser *par, bool doEval)
948 {
949 CondResult res;
950 Token t;
951
952 t = CondParser_Token(par, doEval);
953 if (t == TOK_TRUE)
954 return CR_TRUE;
955 if (t == TOK_FALSE)
956 return CR_FALSE;
957
958 if (t == TOK_LPAREN) {
959 res = CondParser_Or(par, doEval);
960 if (res == CR_ERROR)
961 return CR_ERROR;
962 if (CondParser_Token(par, doEval) != TOK_RPAREN)
963 return CR_ERROR;
964 return res;
965 }
966
967 if (t == TOK_NOT) {
968 res = CondParser_Term(par, doEval);
969 if (res == CR_TRUE)
970 res = CR_FALSE;
971 else if (res == CR_FALSE)
972 res = CR_TRUE;
973 return res;
974 }
975
976 return CR_ERROR;
977 }
978
979 /*
980 * And -> Term
981 * And -> And '&&' Term
982 */
983 static CondResult
984 CondParser_And(CondParser *par, bool doEval)
985 {
986 CondResult res;
987 Token op;
988
989 res = CondParser_Term(par, doEval);
990 if (res == CR_ERROR)
991 return CR_ERROR;
992
993 op = CondParser_Token(par, doEval);
994 if (op == TOK_AND) {
995 if (res == CR_TRUE)
996 return CondParser_And(par, doEval);
997 if (CondParser_And(par, false) == CR_ERROR)
998 return CR_ERROR;
999 return res;
1000 }
1001
1002 CondParser_PushBack(par, op);
1003 return res;
1004 }
1005
1006 /*
1007 * Or -> And
1008 * Or -> Or '||' And
1009 */
1010 static CondResult
1011 CondParser_Or(CondParser *par, bool doEval)
1012 {
1013 CondResult res;
1014 Token op;
1015
1016 res = CondParser_And(par, doEval);
1017 if (res == CR_ERROR)
1018 return CR_ERROR;
1019
1020 op = CondParser_Token(par, doEval);
1021 if (op == TOK_OR) {
1022 if (res == CR_FALSE)
1023 return CondParser_Or(par, doEval);
1024 if (CondParser_Or(par, false) == CR_ERROR)
1025 return CR_ERROR;
1026 return res;
1027 }
1028
1029 CondParser_PushBack(par, op);
1030 return res;
1031 }
1032
1033 static CondEvalResult
1034 CondParser_Eval(CondParser *par, bool *out_value)
1035 {
1036 CondResult res;
1037
1038 DEBUG1(COND, "CondParser_Eval: %s\n", par->p);
1039
1040 res = CondParser_Or(par, true);
1041 if (res == CR_ERROR)
1042 return COND_INVALID;
1043
1044 if (CondParser_Token(par, false) != TOK_EOF)
1045 return COND_INVALID;
1046
1047 *out_value = res == CR_TRUE;
1048 return COND_PARSE;
1049 }
1050
1051 /*
1052 * Evaluate the condition, including any side effects from the variable
1053 * expressions in the condition. The condition consists of &&, ||, !,
1054 * function(arg), comparisons and parenthetical groupings thereof.
1055 *
1056 * Results:
1057 * COND_PARSE if the condition was valid grammatically
1058 * COND_INVALID if not a valid conditional.
1059 *
1060 * (*value) is set to the boolean value of the condition
1061 */
1062 static CondEvalResult
1063 CondEvalExpression(const char *cond, bool *out_value, bool plain,
1064 bool (*evalBare)(size_t, const char *), bool negate,
1065 bool eprint, bool strictLHS)
1066 {
1067 CondParser par;
1068 CondEvalResult rval;
1069
1070 lhsStrict = strictLHS;
1071
1072 cpp_skip_hspace(&cond);
1073
1074 par.plain = plain;
1075 par.evalBare = evalBare;
1076 par.negateEvalBare = negate;
1077 par.p = cond;
1078 par.curr = TOK_NONE;
1079 par.printedError = false;
1080
1081 rval = CondParser_Eval(&par, out_value);
1082
1083 if (rval == COND_INVALID && eprint && !par.printedError)
1084 Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", cond);
1085
1086 return rval;
1087 }
1088
1089 /*
1090 * Evaluate a condition in a :? modifier, such as
1091 * ${"${VAR}" == value:?yes:no}.
1092 */
1093 CondEvalResult
1094 Cond_EvalCondition(const char *cond, bool *out_value)
1095 {
1096 return CondEvalExpression(cond, out_value, true,
1097 FuncDefined, false, false, false);
1098 }
1099
1100 static bool
1101 IsEndif(const char *p)
1102 {
1103 return p[0] == 'e' && p[1] == 'n' && p[2] == 'd' &&
1104 p[3] == 'i' && p[4] == 'f' && !ch_isalpha(p[5]);
1105 }
1106
1107 static bool
1108 DetermineKindOfConditional(const char **pp, bool *out_plain,
1109 bool (**out_evalBare)(size_t, const char *),
1110 bool *out_negate)
1111 {
1112 const char *p = *pp;
1113
1114 p += 2;
1115 *out_plain = false;
1116 *out_evalBare = FuncDefined;
1117 *out_negate = false;
1118 if (*p == 'n') {
1119 p++;
1120 *out_negate = true;
1121 }
1122 if (is_token(p, "def", 3)) { /* .ifdef and .ifndef */
1123 p += 3;
1124 } else if (is_token(p, "make", 4)) { /* .ifmake and .ifnmake */
1125 p += 4;
1126 *out_evalBare = FuncMake;
1127 } else if (is_token(p, "", 0) && !*out_negate) { /* plain .if */
1128 *out_plain = true;
1129 } else {
1130 /*
1131 * TODO: Add error message about unknown directive,
1132 * since there is no other known directive that starts
1133 * with 'el' or 'if'.
1134 *
1135 * Example: .elifx 123
1136 */
1137 return false;
1138 }
1139
1140 *pp = p;
1141 return true;
1142 }
1143
1144 /*
1145 * Evaluate the conditional directive in the line, which is one of:
1146 *
1147 * .if <cond>
1148 * .ifmake <cond>
1149 * .ifnmake <cond>
1150 * .ifdef <cond>
1151 * .ifndef <cond>
1152 * .elif <cond>
1153 * .elifmake <cond>
1154 * .elifnmake <cond>
1155 * .elifdef <cond>
1156 * .elifndef <cond>
1157 * .else
1158 * .endif
1159 *
1160 * In these directives, <cond> consists of &&, ||, !, function(arg),
1161 * comparisons, expressions, bare words, numbers and strings, and
1162 * parenthetical groupings thereof.
1163 *
1164 * Results:
1165 * COND_PARSE to continue parsing the lines that follow the
1166 * conditional (when <cond> evaluates to true)
1167 * COND_SKIP to skip the lines after the conditional
1168 * (when <cond> evaluates to false, or when a previous
1169 * branch has already been taken)
1170 * COND_INVALID if the conditional was not valid, either because of
1171 * a syntax error or because some variable was undefined
1172 * or because the condition could not be evaluated
1173 */
1174 CondEvalResult
1175 Cond_EvalLine(const char *line)
1176 {
1177 typedef enum IfState {
1178
1179 /* None of the previous <cond> evaluated to true. */
1180 IFS_INITIAL = 0,
1181
1182 /* The previous <cond> evaluated to true.
1183 * The lines following this condition are interpreted. */
1184 IFS_ACTIVE = 1 << 0,
1185
1186 /* The previous directive was an '.else'. */
1187 IFS_SEEN_ELSE = 1 << 1,
1188
1189 /* One of the previous <cond> evaluated to true. */
1190 IFS_WAS_ACTIVE = 1 << 2
1191
1192 } IfState;
1193
1194 static enum IfState *cond_states = NULL;
1195 static unsigned int cond_states_cap = 128;
1196
1197 bool plain;
1198 bool (*evalBare)(size_t, const char *);
1199 bool negate;
1200 bool isElif;
1201 bool value;
1202 IfState state;
1203 const char *p = line;
1204
1205 if (cond_states == NULL) {
1206 cond_states = bmake_malloc(
1207 cond_states_cap * sizeof *cond_states);
1208 cond_states[0] = IFS_ACTIVE;
1209 }
1210
1211 p++; /* skip the leading '.' */
1212 cpp_skip_hspace(&p);
1213
1214 if (IsEndif(p)) { /* It is an '.endif'. */
1215 if (p[5] != '\0') {
1216 Parse_Error(PARSE_FATAL,
1217 "The .endif directive does not take arguments.");
1218 }
1219
1220 if (cond_depth == cond_min_depth) {
1221 Parse_Error(PARSE_FATAL, "if-less endif");
1222 return COND_PARSE;
1223 }
1224
1225 /* Return state for previous conditional */
1226 cond_depth--;
1227 return cond_states[cond_depth] & IFS_ACTIVE
1228 ? COND_PARSE : COND_SKIP;
1229 }
1230
1231 /* Parse the name of the directive, such as 'if', 'elif', 'endif'. */
1232 if (p[0] == 'e') {
1233 if (p[1] != 'l') {
1234 /*
1235 * Unknown directive. It might still be a
1236 * transformation rule like '.elisp.scm',
1237 * therefore no error message here.
1238 */
1239 return COND_INVALID;
1240 }
1241
1242 /* Quite likely this is 'else' or 'elif' */
1243 p += 2;
1244 if (is_token(p, "se", 2)) { /* It is an 'else'. */
1245
1246 if (p[2] != '\0')
1247 Parse_Error(PARSE_FATAL,
1248 "The .else directive "
1249 "does not take arguments.");
1250
1251 if (cond_depth == cond_min_depth) {
1252 Parse_Error(PARSE_FATAL, "if-less else");
1253 return COND_PARSE;
1254 }
1255
1256 state = cond_states[cond_depth];
1257 if (state == IFS_INITIAL) {
1258 state = IFS_ACTIVE | IFS_SEEN_ELSE;
1259 } else {
1260 if (state & IFS_SEEN_ELSE)
1261 Parse_Error(PARSE_WARNING,
1262 "extra else");
1263 state = IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
1264 }
1265 cond_states[cond_depth] = state;
1266
1267 return state & IFS_ACTIVE ? COND_PARSE : COND_SKIP;
1268 }
1269 /* Assume for now it is an elif */
1270 isElif = true;
1271 } else
1272 isElif = false;
1273
1274 if (p[0] != 'i' || p[1] != 'f') {
1275 /*
1276 * Unknown directive. It might still be a transformation rule
1277 * like '.elisp.scm', therefore no error message here.
1278 */
1279 return COND_INVALID; /* Not an ifxxx or elifxxx line */
1280 }
1281
1282 if (!DetermineKindOfConditional(&p, &plain, &evalBare, &negate))
1283 return COND_INVALID;
1284
1285 if (isElif) {
1286 if (cond_depth == cond_min_depth) {
1287 Parse_Error(PARSE_FATAL, "if-less elif");
1288 return COND_PARSE;
1289 }
1290 state = cond_states[cond_depth];
1291 if (state & IFS_SEEN_ELSE) {
1292 Parse_Error(PARSE_WARNING, "extra elif");
1293 cond_states[cond_depth] =
1294 IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
1295 return COND_SKIP;
1296 }
1297 if (state != IFS_INITIAL) {
1298 cond_states[cond_depth] = IFS_WAS_ACTIVE;
1299 return COND_SKIP;
1300 }
1301 } else {
1302 /* Normal .if */
1303 if (cond_depth + 1 >= cond_states_cap) {
1304 /*
1305 * This is rare, but not impossible.
1306 * In meta mode, dirdeps.mk (only runs at level 0)
1307 * can need more than the default.
1308 */
1309 cond_states_cap += 32;
1310 cond_states = bmake_realloc(cond_states,
1311 cond_states_cap *
1312 sizeof *cond_states);
1313 }
1314 state = cond_states[cond_depth];
1315 cond_depth++;
1316 if (!(state & IFS_ACTIVE)) {
1317 /*
1318 * If we aren't parsing the data,
1319 * treat as always false.
1320 */
1321 cond_states[cond_depth] = IFS_WAS_ACTIVE;
1322 return COND_SKIP;
1323 }
1324 }
1325
1326 /* And evaluate the conditional expression */
1327 if (CondEvalExpression(p, &value, plain, evalBare, negate,
1328 true, true) == COND_INVALID) {
1329 /* Syntax error in conditional, error message already output. */
1330 /* Skip everything to matching .endif */
1331 /* XXX: An extra '.else' is not detected in this case. */
1332 cond_states[cond_depth] = IFS_WAS_ACTIVE;
1333 return COND_SKIP;
1334 }
1335
1336 if (!value) {
1337 cond_states[cond_depth] = IFS_INITIAL;
1338 return COND_SKIP;
1339 }
1340 cond_states[cond_depth] = IFS_ACTIVE;
1341 return COND_PARSE;
1342 }
1343
1344 void
1345 Cond_restore_depth(unsigned int saved_depth)
1346 {
1347 unsigned int open_conds = cond_depth - cond_min_depth;
1348
1349 if (open_conds != 0 || saved_depth > cond_depth) {
1350 Parse_Error(PARSE_FATAL, "%u open conditional%s",
1351 open_conds, open_conds == 1 ? "" : "s");
1352 cond_depth = cond_min_depth;
1353 }
1354
1355 cond_min_depth = saved_depth;
1356 }
1357
1358 unsigned int
1359 Cond_save_depth(void)
1360 {
1361 unsigned int depth = cond_min_depth;
1362
1363 cond_min_depth = cond_depth;
1364 return depth;
1365 }
1366