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