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