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