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