Hiding pointer in typedefs is evil. 'Buffer *' -> 'Buffer'
[dragonfly.git] / usr.bin / make / cond.c
CommitLineData
984263bc 1/*
9a309bcc
MD
2 * Copyright (c) 1988, 1989, 1990, 1993
3 * The Regents of the University of California. All rights reserved.
984263bc
MD
4 * Copyright (c) 1988, 1989 by Adam de Boor
5 * Copyright (c) 1989 by Berkeley Softworks
6 * All rights reserved.
7 *
8 * This code is derived from software contributed to Berkeley by
9 * Adam de Boor.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * SUCH DAMAGE.
1de703da
MD
38 *
39 * @(#)cond.c 8.2 (Berkeley) 1/2/94
27afa3b2 40 * $FreeBSD: src/usr.bin/make/cond.c,v 1.12.2.1 2003/07/22 08:03:13 ru Exp $
6a3d9147 41 * $DragonFly: src/usr.bin/make/cond.c,v 1.20 2005/01/06 13:18:58 okumoto Exp $
984263bc
MD
42 */
43
984263bc
MD
44/*-
45 * cond.c --
46 * Functions to handle conditionals in a makefile.
47 *
48 * Interface:
49 * Cond_Eval Evaluate the conditional in the passed line.
50 *
51 */
52
9863ce62
MO
53#include <stdio.h>
54#include <stdlib.h>
55#include <string.h>
56#include <ctype.h>
57
6a3d9147 58#include "buf.h"
9863ce62
MO
59#include "cond.h"
60#include "dir.h"
61#include "globals.h"
62#include "GNode.h"
63#include "make.h"
64#include "parse.h"
65#include "sprite.h"
66#include "str.h"
67#include "targ.h"
68#include "util.h"
69#include "var.h"
984263bc
MD
70
71/*
72 * The parsing of conditional expressions is based on this grammar:
73 * E -> F || E
74 * E -> F
75 * F -> T && F
76 * F -> T
77 * T -> defined(variable)
78 * T -> make(target)
79 * T -> exists(file)
80 * T -> empty(varspec)
81 * T -> target(name)
82 * T -> symbol
83 * T -> $(varspec) op value
84 * T -> $(varspec) == "string"
85 * T -> $(varspec) != "string"
86 * T -> ( E )
87 * T -> ! T
88 * op -> == | != | > | < | >= | <=
89 *
90 * 'symbol' is some other symbol to which the default function (condDefProc)
91 * is applied.
92 *
93 * Tokens are scanned from the 'condExpr' string. The scanner (CondToken)
94 * will return And for '&' and '&&', Or for '|' and '||', Not for '!',
95 * LParen for '(', RParen for ')' and will evaluate the other terminal
96 * symbols, using either the default function or the function given in the
97 * terminal, and return the result as either True or False.
98 *
99 * All Non-Terminal functions (CondE, CondF and CondT) return Err on error.
100 */
101typedef enum {
102 And, Or, Not, True, False, LParen, RParen, EndOfFile, None, Err
103} Token;
104
105/*-
106 * Structures to handle elegantly the different forms of #if's. The
107 * last two fields are stored in condInvert and condDefProc, respectively.
108 */
2d8a3be7
EN
109static void CondPushBack(Token);
110static int CondGetArg(char **, char **, char *, Boolean);
111static Boolean CondDoDefined(int, char *);
2d8a3be7
EN
112static Boolean CondDoMake(int, char *);
113static Boolean CondDoExists(int, char *);
114static Boolean CondDoTarget(int, char *);
115static char * CondCvtArg(char *, double *);
116static Token CondToken(Boolean);
117static Token CondT(Boolean);
118static Token CondF(Boolean);
119static Token CondE(Boolean);
984263bc
MD
120
121static struct If {
122 char *form; /* Form of if */
123 int formlen; /* Length of form */
124 Boolean doNot; /* TRUE if default function should be negated */
2d8a3be7 125 Boolean (*defProc)(int, char *); /* Default function to apply */
984263bc
MD
126} ifs[] = {
127 { "ifdef", 5, FALSE, CondDoDefined },
128 { "ifndef", 6, TRUE, CondDoDefined },
129 { "ifmake", 6, FALSE, CondDoMake },
130 { "ifnmake", 7, TRUE, CondDoMake },
131 { "if", 2, FALSE, CondDoDefined },
132 { NULL, 0, FALSE, NULL }
133};
134
135static Boolean condInvert; /* Invert the default function */
136static Boolean (*condDefProc) /* Default function to apply */
b83dbac0 137(int, char *);
984263bc
MD
138static char *condExpr; /* The expression to parse */
139static Token condPushBack=None; /* Single push-back token used in
140 * parsing */
141
142#define MAXIF 30 /* greatest depth of #if'ing */
143
144static Boolean condStack[MAXIF]; /* Stack of conditionals's values */
92490377 145static int condLineno[MAXIF]; /* Line numbers of the opening .if */
984263bc
MD
146static int condTop = MAXIF; /* Top-most conditional */
147static int skipIfLevel=0; /* Depth of skipped conditionals */
92490377 148static int skipIfLineno[MAXIF]; /* Line numbers of skipped .ifs */
984263bc
MD
149static Boolean skipLine = FALSE; /* Whether the parse module is skipping
150 * lines */
151
152/*-
153 *-----------------------------------------------------------------------
154 * CondPushBack --
155 * Push back the most recent token read. We only need one level of
156 * this, so the thing is just stored in 'condPushback'.
157 *
158 * Results:
159 * None.
160 *
161 * Side Effects:
162 * condPushback is overwritten.
163 *
164 *-----------------------------------------------------------------------
165 */
166static void
fbfaa208 167CondPushBack(Token t)
984263bc 168{
9a4c88c2 169
984263bc
MD
170 condPushBack = t;
171}
fbfaa208 172
984263bc
MD
173/*-
174 *-----------------------------------------------------------------------
175 * CondGetArg --
84de9e23
MD
176 * Find the argument of a built-in function. parens is set to TRUE
177 * if the arguments are bounded by parens.
984263bc
MD
178 *
179 * Results:
180 * The length of the argument and the address of the argument.
181 *
182 * Side Effects:
183 * The pointer is set to point to the closing parenthesis of the
184 * function call.
185 *
186 *-----------------------------------------------------------------------
187 */
188static int
fbfaa208 189CondGetArg(char **linePtr, char **argPtr, char *func, Boolean parens)
984263bc 190{
9a309bcc 191 char *cp;
9cf296a4 192 size_t argLen;
6a3d9147 193 Buffer *buf;
984263bc
MD
194
195 cp = *linePtr;
196 if (parens) {
197 while (*cp != '(' && *cp != '\0') {
198 cp++;
199 }
200 if (*cp == '(') {
201 cp++;
202 }
203 }
204
205 if (*cp == '\0') {
206 /*
207 * No arguments whatsoever. Because 'make' and 'defined' aren't really
208 * "reserved words", we don't print a message. I think this is better
209 * than hitting the user with a warning message every time s/he uses
210 * the word 'make' or 'defined' at the beginning of a symbol...
211 */
212 *argPtr = cp;
213 return (0);
214 }
215
216 while (*cp == ' ' || *cp == '\t') {
217 cp++;
218 }
219
220 /*
221 * Create a buffer for the argument and start it out at 16 characters
222 * long. Why 16? Why not?
223 */
224 buf = Buf_Init(16);
225
9a4c88c2 226 while ((strchr(" \t)&|", *cp) == NULL) && (*cp != '\0')) {
984263bc
MD
227 if (*cp == '$') {
228 /*
229 * Parse the variable spec and install it as part of the argument
230 * if it's valid. We tell Var_Parse to complain on an undefined
231 * variable, so we don't do it too. Nor do we return an error,
232 * though perhaps we should...
233 */
234 char *cp2;
9cf296a4 235 size_t len;
984263bc
MD
236 Boolean doFree;
237
238 cp2 = Var_Parse(cp, VAR_CMD, TRUE, &len, &doFree);
239
240 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
241 if (doFree) {
242 free(cp2);
243 }
244 cp += len;
245 } else {
246 Buf_AddByte(buf, (Byte)*cp);
247 cp++;
248 }
249 }
250
251 Buf_AddByte(buf, (Byte)'\0');
252 *argPtr = (char *)Buf_GetAll(buf, &argLen);
253 Buf_Destroy(buf, FALSE);
254
255 while (*cp == ' ' || *cp == '\t') {
256 cp++;
257 }
258 if (parens && *cp != ')') {
fbfaa208 259 Parse_Error(PARSE_WARNING, "Missing closing parenthesis for %s()",
984263bc
MD
260 func);
261 return (0);
262 } else if (parens) {
263 /*
264 * Advance pointer past close parenthesis.
265 */
266 cp++;
267 }
268
269 *linePtr = cp;
270 return (argLen);
271}
fbfaa208 272
984263bc
MD
273/*-
274 *-----------------------------------------------------------------------
275 * CondDoDefined --
276 * Handle the 'defined' function for conditionals.
277 *
278 * Results:
279 * TRUE if the given variable is defined.
280 *
281 * Side Effects:
282 * None.
283 *
284 *-----------------------------------------------------------------------
285 */
286static Boolean
fbfaa208 287CondDoDefined(int argLen, char *arg)
984263bc
MD
288{
289 char savec = arg[argLen];
290 char *p1;
291 Boolean result;
292
293 arg[argLen] = '\0';
9a4c88c2 294 if (Var_Value(arg, VAR_CMD, &p1) != NULL) {
984263bc
MD
295 result = TRUE;
296 } else {
297 result = FALSE;
298 }
a4516861 299 free(p1);
984263bc
MD
300 arg[argLen] = savec;
301 return (result);
302}
fbfaa208 303
984263bc
MD
304/*-
305 *-----------------------------------------------------------------------
306 * CondStrMatch --
307 * Front-end for Str_Match so it returns 0 on match and non-zero
308 * on mismatch. Callback function for CondDoMake via Lst_Find
309 *
310 * Results:
311 * 0 if string matches pattern
312 *
313 * Side Effects:
314 * None
315 *
316 *-----------------------------------------------------------------------
317 */
318static int
d98710ab 319CondStrMatch(const void *string, const void *pattern)
984263bc 320{
9a4c88c2 321
d98710ab 322 return (!Str_Match(string, pattern));
984263bc 323}
fbfaa208 324
984263bc
MD
325/*-
326 *-----------------------------------------------------------------------
327 * CondDoMake --
328 * Handle the 'make' function for conditionals.
329 *
330 * Results:
331 * TRUE if the given target is being made.
332 *
333 * Side Effects:
334 * None.
335 *
336 *-----------------------------------------------------------------------
337 */
338static Boolean
fbfaa208 339CondDoMake(int argLen, char *arg)
984263bc
MD
340{
341 char savec = arg[argLen];
342 Boolean result;
343
344 arg[argLen] = '\0';
0a7e0b85 345 if (Lst_Find(&create, arg, CondStrMatch) == NULL) {
984263bc
MD
346 result = FALSE;
347 } else {
348 result = TRUE;
349 }
350 arg[argLen] = savec;
351 return (result);
352}
fbfaa208 353
984263bc
MD
354/*-
355 *-----------------------------------------------------------------------
356 * CondDoExists --
357 * See if the given file exists.
358 *
359 * Results:
360 * TRUE if the file exists and FALSE if it does not.
361 *
362 * Side Effects:
363 * None.
364 *
365 *-----------------------------------------------------------------------
366 */
367static Boolean
fbfaa208 368CondDoExists(int argLen, char *arg)
984263bc
MD
369{
370 char savec = arg[argLen];
371 Boolean result;
372 char *path;
373
374 arg[argLen] = '\0';
0a7e0b85 375 path = Dir_FindFile(arg, &dirSearchPath);
9a4c88c2 376 if (path != NULL) {
984263bc
MD
377 result = TRUE;
378 free(path);
379 } else {
380 result = FALSE;
381 }
382 arg[argLen] = savec;
383 return (result);
384}
fbfaa208 385
984263bc
MD
386/*-
387 *-----------------------------------------------------------------------
388 * CondDoTarget --
389 * See if the given node exists and is an actual target.
390 *
391 * Results:
392 * TRUE if the node exists as a target and FALSE if it does not.
393 *
394 * Side Effects:
395 * None.
396 *
397 *-----------------------------------------------------------------------
398 */
399static Boolean
fbfaa208 400CondDoTarget(int argLen, char *arg)
984263bc
MD
401{
402 char savec = arg[argLen];
403 Boolean result;
404 GNode *gn;
405
406 arg[argLen] = '\0';
407 gn = Targ_FindNode(arg, TARG_NOCREATE);
9edd457e 408 if ((gn != NULL) && !OP_NOP(gn->type)) {
984263bc
MD
409 result = TRUE;
410 } else {
411 result = FALSE;
412 }
413 arg[argLen] = savec;
414 return (result);
415}
416
984263bc
MD
417/*-
418 *-----------------------------------------------------------------------
419 * CondCvtArg --
420 * Convert the given number into a double. If the number begins
421 * with 0x, it is interpreted as a hexadecimal integer
422 * and converted to a double from there. All other strings just have
423 * strtod called on them.
424 *
425 * Results:
426 * Sets 'value' to double value of string.
427 * Returns address of the first character after the last valid
428 * character of the converted number.
429 *
430 * Side Effects:
431 * Can change 'value' even if string is not a valid number.
432 *
433 *
434 *-----------------------------------------------------------------------
435 */
436static char *
84de9e23 437CondCvtArg(char *str, double *value)
984263bc
MD
438{
439 if ((*str == '0') && (str[1] == 'x')) {
9a309bcc 440 long i;
984263bc
MD
441
442 for (str += 2, i = 0; ; str++) {
443 int x;
fbfaa208 444 if (isdigit((unsigned char)*str))
984263bc 445 x = *str - '0';
fbfaa208
MO
446 else if (isxdigit((unsigned char)*str))
447 x = 10 + *str - isupper((unsigned char)*str) ? 'A' : 'a';
984263bc 448 else {
fbfaa208 449 *value = (double)i;
9a4c88c2 450 return (str);
984263bc
MD
451 }
452 i = (i << 4) + x;
453 }
454 }
455 else {
456 char *eptr;
457 *value = strtod(str, &eptr);
fbfaa208 458 return (eptr);
984263bc
MD
459 }
460}
fbfaa208 461
984263bc
MD
462/*-
463 *-----------------------------------------------------------------------
464 * CondToken --
465 * Return the next token from the input.
466 *
467 * Results:
468 * A Token for the next lexical token in the stream.
469 *
470 * Side Effects:
471 * condPushback will be set back to None if it is used.
472 *
473 *-----------------------------------------------------------------------
474 */
475static Token
84de9e23 476CondToken(Boolean doEval)
984263bc
MD
477{
478 Token t;
479
480 if (condPushBack == None) {
481 while (*condExpr == ' ' || *condExpr == '\t') {
482 condExpr++;
483 }
484 switch (*condExpr) {
485 case '(':
486 t = LParen;
487 condExpr++;
488 break;
489 case ')':
490 t = RParen;
491 condExpr++;
492 break;
493 case '|':
494 if (condExpr[1] == '|') {
495 condExpr++;
496 }
497 condExpr++;
498 t = Or;
499 break;
500 case '&':
501 if (condExpr[1] == '&') {
502 condExpr++;
503 }
504 condExpr++;
505 t = And;
506 break;
507 case '!':
508 t = Not;
509 condExpr++;
510 break;
511 case '\n':
512 case '\0':
513 t = EndOfFile;
514 break;
515 case '$': {
516 char *lhs;
517 char *rhs;
518 char *op;
9cf296a4 519 size_t varSpecLen;
984263bc
MD
520 Boolean doFree;
521
522 /*
523 * Parse the variable spec and skip over it, saving its
524 * value in lhs.
525 */
526 t = Err;
fbfaa208
MO
527 lhs = Var_Parse(condExpr, VAR_CMD, doEval,
528 &varSpecLen, &doFree);
984263bc
MD
529 if (lhs == var_Error) {
530 /*
531 * Even if !doEval, we still report syntax errors, which
532 * is what getting var_Error back with !doEval means.
533 */
fbfaa208 534 return (Err);
984263bc
MD
535 }
536 condExpr += varSpecLen;
537
fbfaa208 538 if (!isspace((unsigned char)*condExpr) &&
984263bc 539 strchr("!=><", *condExpr) == NULL) {
6a3d9147 540 Buffer *buf;
984263bc
MD
541 char *cp;
542
543 buf = Buf_Init(0);
544
545 for (cp = lhs; *cp; cp++)
546 Buf_AddByte(buf, (Byte)*cp);
547
548 if (doFree)
549 free(lhs);
550
551 for (;*condExpr && !isspace((unsigned char) *condExpr);
552 condExpr++)
553 Buf_AddByte(buf, (Byte)*condExpr);
554
555 Buf_AddByte(buf, (Byte)'\0');
556 lhs = (char *)Buf_GetAll(buf, &varSpecLen);
557 Buf_Destroy(buf, FALSE);
558
559 doFree = TRUE;
560 }
561
562 /*
563 * Skip whitespace to get to the operator
564 */
fbfaa208 565 while (isspace((unsigned char)*condExpr))
984263bc
MD
566 condExpr++;
567
568 /*
569 * Make sure the operator is a valid one. If it isn't a
570 * known relational operator, pretend we got a
571 * != 0 comparison.
572 */
573 op = condExpr;
574 switch (*condExpr) {
575 case '!':
576 case '=':
577 case '<':
578 case '>':
579 if (condExpr[1] == '=') {
580 condExpr += 2;
581 } else {
582 condExpr += 1;
583 }
584 break;
585 default:
586 op = "!=";
587 rhs = "0";
588
589 goto do_compare;
590 }
fbfaa208 591 while (isspace((unsigned char)*condExpr)) {
984263bc
MD
592 condExpr++;
593 }
594 if (*condExpr == '\0') {
595 Parse_Error(PARSE_WARNING,
596 "Missing right-hand-side of operator");
597 goto error;
598 }
599 rhs = condExpr;
600do_compare:
601 if (*rhs == '"') {
602 /*
603 * Doing a string comparison. Only allow == and != for
604 * operators.
605 */
606 char *string;
607 char *cp, *cp2;
608 int qt;
6a3d9147 609 Buffer *buf;
984263bc
MD
610
611do_string_compare:
612 if (((*op != '!') && (*op != '=')) || (op[1] != '=')) {
613 Parse_Error(PARSE_WARNING,
614 "String comparison operator should be either == or !=");
615 goto error;
616 }
617
618 buf = Buf_Init(0);
619 qt = *rhs == '"' ? 1 : 0;
620
621 for (cp = &rhs[qt];
622 ((qt && (*cp != '"')) ||
623 (!qt && strchr(" \t)", *cp) == NULL)) &&
624 (*cp != '\0'); cp++) {
625 if ((*cp == '\\') && (cp[1] != '\0')) {
626 /*
627 * Backslash escapes things -- skip over next
628 * character, if it exists.
629 */
630 cp++;
631 Buf_AddByte(buf, (Byte)*cp);
632 } else if (*cp == '$') {
9cf296a4 633 size_t len;
984263bc
MD
634 Boolean freeIt;
635
fbfaa208 636 cp2 = Var_Parse(cp, VAR_CMD, doEval, &len, &freeIt);
984263bc
MD
637 if (cp2 != var_Error) {
638 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
639 if (freeIt) {
640 free(cp2);
641 }
642 cp += len - 1;
643 } else {
644 Buf_AddByte(buf, (Byte)*cp);
645 }
646 } else {
647 Buf_AddByte(buf, (Byte)*cp);
648 }
649 }
650
651 Buf_AddByte(buf, (Byte)0);
652
9cf296a4 653 string = (char *)Buf_GetAll(buf, (size_t *)NULL);
984263bc
MD
654 Buf_Destroy(buf, FALSE);
655
913800f5
MD
656 DEBUGF(COND, ("lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
657 lhs, string, op));
984263bc
MD
658 /*
659 * Null-terminate rhs and perform the comparison.
660 * t is set to the result.
661 */
662 if (*op == '=') {
663 t = strcmp(lhs, string) ? False : True;
664 } else {
665 t = strcmp(lhs, string) ? True : False;
666 }
667 free(string);
668 if (rhs == condExpr) {
669 if (!qt && *cp == ')')
670 condExpr = cp;
671 else
672 condExpr = cp + 1;
673 }
674 } else {
675 /*
676 * rhs is either a float or an integer. Convert both the
677 * lhs and the rhs to a double and compare the two.
678 */
679 double left, right;
680 char *string;
681
682 if (*CondCvtArg(lhs, &left) != '\0')
683 goto do_string_compare;
684 if (*rhs == '$') {
9cf296a4 685 size_t len;
984263bc
MD
686 Boolean freeIt;
687
fbfaa208 688 string = Var_Parse(rhs, VAR_CMD, doEval, &len, &freeIt);
984263bc
MD
689 if (string == var_Error) {
690 right = 0.0;
691 } else {
692 if (*CondCvtArg(string, &right) != '\0') {
693 if (freeIt)
694 free(string);
695 goto do_string_compare;
696 }
697 if (freeIt)
698 free(string);
699 if (rhs == condExpr)
700 condExpr += len;
701 }
702 } else {
703 char *c = CondCvtArg(rhs, &right);
27afa3b2 704 if (c == rhs)
984263bc
MD
705 goto do_string_compare;
706 if (rhs == condExpr) {
707 /*
708 * Skip over the right-hand side
709 */
27afa3b2 710 condExpr = c;
984263bc
MD
711 }
712 }
713
913800f5
MD
714 DEBUGF(COND, ("left = %f, right = %f, op = %.2s\n", left,
715 right, op));
fbfaa208 716 switch (op[0]) {
984263bc
MD
717 case '!':
718 if (op[1] != '=') {
719 Parse_Error(PARSE_WARNING,
720 "Unknown operator");
721 goto error;
722 }
723 t = (left != right ? True : False);
724 break;
725 case '=':
726 if (op[1] != '=') {
727 Parse_Error(PARSE_WARNING,
728 "Unknown operator");
729 goto error;
730 }
731 t = (left == right ? True : False);
732 break;
733 case '<':
734 if (op[1] == '=') {
735 t = (left <= right ? True : False);
736 } else {
737 t = (left < right ? True : False);
738 }
739 break;
740 case '>':
741 if (op[1] == '=') {
742 t = (left >= right ? True : False);
743 } else {
744 t = (left > right ? True : False);
745 }
746 break;
454224cf
MD
747 default:
748 break;
984263bc
MD
749 }
750 }
751error:
752 if (doFree)
753 free(lhs);
754 break;
755 }
756 default: {
2d8a3be7 757 Boolean (*evalProc)(int, char *);
984263bc
MD
758 Boolean invert = FALSE;
759 char *arg;
760 int arglen;
761
fbfaa208 762 if (strncmp(condExpr, "defined", 7) == 0) {
984263bc
MD
763 /*
764 * Use CondDoDefined to evaluate the argument and
765 * CondGetArg to extract the argument from the 'function
766 * call'.
767 */
768 evalProc = CondDoDefined;
769 condExpr += 7;
fbfaa208 770 arglen = CondGetArg(&condExpr, &arg, "defined", TRUE);
984263bc
MD
771 if (arglen == 0) {
772 condExpr -= 7;
773 goto use_default;
774 }
fbfaa208 775 } else if (strncmp(condExpr, "make", 4) == 0) {
984263bc
MD
776 /*
777 * Use CondDoMake to evaluate the argument and
778 * CondGetArg to extract the argument from the 'function
779 * call'.
780 */
781 evalProc = CondDoMake;
782 condExpr += 4;
fbfaa208 783 arglen = CondGetArg(&condExpr, &arg, "make", TRUE);
984263bc
MD
784 if (arglen == 0) {
785 condExpr -= 4;
786 goto use_default;
787 }
fbfaa208 788 } else if (strncmp(condExpr, "exists", 6) == 0) {
984263bc
MD
789 /*
790 * Use CondDoExists to evaluate the argument and
791 * CondGetArg to extract the argument from the
792 * 'function call'.
793 */
794 evalProc = CondDoExists;
795 condExpr += 6;
796 arglen = CondGetArg(&condExpr, &arg, "exists", TRUE);
797 if (arglen == 0) {
798 condExpr -= 6;
799 goto use_default;
800 }
801 } else if (strncmp(condExpr, "empty", 5) == 0) {
802 /*
803 * Use Var_Parse to parse the spec in parens and return
804 * True if the resulting string is empty.
805 */
9cf296a4 806 size_t length;
984263bc
MD
807 Boolean doFree;
808 char *val;
809
810 condExpr += 5;
811
812 for (arglen = 0;
813 condExpr[arglen] != '(' && condExpr[arglen] != '\0';
814 arglen += 1)
815 continue;
816
817 if (condExpr[arglen] != '\0') {
818 val = Var_Parse(&condExpr[arglen - 1], VAR_CMD,
4bd279b8 819 FALSE, &length, &doFree);
984263bc
MD
820 if (val == var_Error) {
821 t = Err;
822 } else {
823 /*
824 * A variable is empty when it just contains
825 * spaces... 4/15/92, christos
826 */
827 char *p;
828 for (p = val; *p && isspace((unsigned char)*p); p++)
829 continue;
830 t = (*p == '\0') ? True : False;
831 }
832 if (doFree) {
833 free(val);
834 }
835 /*
836 * Advance condExpr to beyond the closing ). Note that
837 * we subtract one from arglen + length b/c length
838 * is calculated from condExpr[arglen - 1].
839 */
840 condExpr += arglen + length - 1;
841 } else {
842 condExpr -= 5;
843 goto use_default;
844 }
845 break;
fbfaa208 846 } else if (strncmp(condExpr, "target", 6) == 0) {
984263bc
MD
847 /*
848 * Use CondDoTarget to evaluate the argument and
849 * CondGetArg to extract the argument from the
850 * 'function call'.
851 */
852 evalProc = CondDoTarget;
853 condExpr += 6;
854 arglen = CondGetArg(&condExpr, &arg, "target", TRUE);
855 if (arglen == 0) {
856 condExpr -= 6;
857 goto use_default;
858 }
859 } else {
860 /*
861 * The symbol is itself the argument to the default
862 * function. We advance condExpr to the end of the symbol
863 * by hand (the next whitespace, closing paren or
864 * binary operator) and set to invert the evaluation
865 * function if condInvert is TRUE.
866 */
867 use_default:
868 invert = condInvert;
869 evalProc = condDefProc;
870 arglen = CondGetArg(&condExpr, &arg, "", FALSE);
871 }
872
873 /*
874 * Evaluate the argument using the set function. If invert
875 * is TRUE, we invert the sense of the function.
876 */
877 t = (!doEval || (* evalProc) (arglen, arg) ?
878 (invert ? False : True) :
879 (invert ? True : False));
880 free(arg);
881 break;
882 }
883 }
884 } else {
885 t = condPushBack;
886 condPushBack = None;
887 }
888 return (t);
889}
fbfaa208 890
984263bc
MD
891/*-
892 *-----------------------------------------------------------------------
893 * CondT --
894 * Parse a single term in the expression. This consists of a terminal
895 * symbol or Not and a terminal symbol (not including the binary
896 * operators):
897 * T -> defined(variable) | make(target) | exists(file) | symbol
898 * T -> ! T | ( E )
899 *
900 * Results:
901 * True, False or Err.
902 *
903 * Side Effects:
904 * Tokens are consumed.
905 *
906 *-----------------------------------------------------------------------
907 */
908static Token
84de9e23 909CondT(Boolean doEval)
984263bc
MD
910{
911 Token t;
912
913 t = CondToken(doEval);
914
915 if (t == EndOfFile) {
916 /*
917 * If we reached the end of the expression, the expression
918 * is malformed...
919 */
920 t = Err;
921 } else if (t == LParen) {
922 /*
923 * T -> ( E )
924 */
925 t = CondE(doEval);
926 if (t != Err) {
927 if (CondToken(doEval) != RParen) {
928 t = Err;
929 }
930 }
931 } else if (t == Not) {
932 t = CondT(doEval);
933 if (t == True) {
934 t = False;
935 } else if (t == False) {
936 t = True;
937 }
938 }
939 return (t);
940}
fbfaa208 941
984263bc
MD
942/*-
943 *-----------------------------------------------------------------------
944 * CondF --
945 * Parse a conjunctive factor (nice name, wot?)
946 * F -> T && F | T
947 *
948 * Results:
949 * True, False or Err
950 *
951 * Side Effects:
952 * Tokens are consumed.
953 *
954 *-----------------------------------------------------------------------
955 */
956static Token
84de9e23 957CondF(Boolean doEval)
984263bc
MD
958{
959 Token l, o;
960
961 l = CondT(doEval);
962 if (l != Err) {
963 o = CondToken(doEval);
964
965 if (o == And) {
966 /*
967 * F -> T && F
968 *
969 * If T is False, the whole thing will be False, but we have to
970 * parse the r.h.s. anyway (to throw it away).
971 * If T is True, the result is the r.h.s., be it an Err or no.
972 */
973 if (l == True) {
974 l = CondF(doEval);
975 } else {
fbfaa208 976 CondF(FALSE);
984263bc
MD
977 }
978 } else {
979 /*
980 * F -> T
981 */
fbfaa208 982 CondPushBack(o);
984263bc
MD
983 }
984 }
985 return (l);
986}
fbfaa208 987
984263bc
MD
988/*-
989 *-----------------------------------------------------------------------
990 * CondE --
991 * Main expression production.
992 * E -> F || E | F
993 *
994 * Results:
995 * True, False or Err.
996 *
997 * Side Effects:
998 * Tokens are, of course, consumed.
999 *
1000 *-----------------------------------------------------------------------
1001 */
1002static Token
84de9e23 1003CondE(Boolean doEval)
984263bc
MD
1004{
1005 Token l, o;
1006
1007 l = CondF(doEval);
1008 if (l != Err) {
1009 o = CondToken(doEval);
1010
1011 if (o == Or) {
1012 /*
1013 * E -> F || E
1014 *
1015 * A similar thing occurs for ||, except that here we make sure
1016 * the l.h.s. is False before we bother to evaluate the r.h.s.
1017 * Once again, if l is False, the result is the r.h.s. and once
1018 * again if l is True, we parse the r.h.s. to throw it away.
1019 */
1020 if (l == False) {
1021 l = CondE(doEval);
1022 } else {
fbfaa208 1023 CondE(FALSE);
984263bc
MD
1024 }
1025 } else {
1026 /*
1027 * E -> F
1028 */
fbfaa208 1029 CondPushBack(o);
984263bc
MD
1030 }
1031 }
1032 return (l);
1033}
fbfaa208 1034
984263bc
MD
1035/*-
1036 *-----------------------------------------------------------------------
1037 * Cond_Eval --
1038 * Evaluate the conditional in the passed line. The line
1039 * looks like this:
1040 * #<cond-type> <expr>
1041 * where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1042 * ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1043 * and <expr> consists of &&, ||, !, make(target), defined(variable)
1044 * and parenthetical groupings thereof.
1045 *
1046 * Results:
1047 * COND_PARSE if should parse lines after the conditional
1048 * COND_SKIP if should skip lines after the conditional
1049 * COND_INVALID if not a valid conditional.
1050 *
1051 * Side Effects:
1052 * None.
1053 *
1054 *-----------------------------------------------------------------------
1055 */
1056int
fbfaa208 1057Cond_Eval(char *line)
984263bc
MD
1058{
1059 struct If *ifp;
1060 Boolean isElse;
1061 Boolean value = FALSE;
1062 int level; /* Level at which to report errors. */
92490377 1063 int lineno;
984263bc
MD
1064
1065 level = PARSE_FATAL;
92490377 1066 lineno = curFile.lineno;
984263bc
MD
1067
1068 for (line++; *line == ' ' || *line == '\t'; line++) {
1069 continue;
1070 }
1071
1072 /*
1073 * Find what type of if we're dealing with. The result is left
1074 * in ifp and isElse is set TRUE if it's an elif line.
1075 */
1076 if (line[0] == 'e' && line[1] == 'l') {
1077 line += 2;
1078 isElse = TRUE;
fbfaa208 1079 } else if (strncmp(line, "endif", 5) == 0) {
984263bc
MD
1080 /*
1081 * End of a conditional section. If skipIfLevel is non-zero, that
1082 * conditional was skipped, so lines following it should also be
1083 * skipped. Hence, we return COND_SKIP. Otherwise, the conditional
1084 * was read so succeeding lines should be parsed (think about it...)
1085 * so we return COND_PARSE, unless this endif isn't paired with
1086 * a decent if.
1087 */
1088 if (skipIfLevel != 0) {
1089 skipIfLevel -= 1;
1090 return (COND_SKIP);
1091 } else {
1092 if (condTop == MAXIF) {
fbfaa208 1093 Parse_Error(level, "if-less endif");
984263bc
MD
1094 return (COND_INVALID);
1095 } else {
1096 skipLine = FALSE;
1097 condTop += 1;
1098 return (COND_PARSE);
1099 }
1100 }
1101 } else {
1102 isElse = FALSE;
1103 }
1104
1105 /*
1106 * Figure out what sort of conditional it is -- what its default
1107 * function is, etc. -- by looking in the table of valid "ifs"
1108 */
9a4c88c2 1109 for (ifp = ifs; ifp->form != NULL; ifp++) {
fbfaa208 1110 if (strncmp(ifp->form, line, ifp->formlen) == 0) {
984263bc
MD
1111 break;
1112 }
1113 }
1114
9a4c88c2 1115 if (ifp->form == NULL) {
984263bc
MD
1116 /*
1117 * Nothing fit. If the first word on the line is actually
1118 * "else", it's a valid conditional whose value is the inverse
1119 * of the previous if we parsed.
1120 */
1121 if (isElse && (line[0] == 's') && (line[1] == 'e')) {
1122 if (condTop == MAXIF) {
fbfaa208 1123 Parse_Error(level, "if-less else");
984263bc
MD
1124 return (COND_INVALID);
1125 } else if (skipIfLevel == 0) {
1126 value = !condStack[condTop];
92490377 1127 lineno = condLineno[condTop];
984263bc
MD
1128 } else {
1129 return (COND_SKIP);
1130 }
1131 } else {
1132 /*
1133 * Not a valid conditional type. No error...
1134 */
1135 return (COND_INVALID);
1136 }
1137 } else {
1138 if (isElse) {
1139 if (condTop == MAXIF) {
fbfaa208 1140 Parse_Error(level, "if-less elif");
984263bc
MD
1141 return (COND_INVALID);
1142 } else if (skipIfLevel != 0) {
1143 /*
1144 * If skipping this conditional, just ignore the whole thing.
1145 * If we don't, the user might be employing a variable that's
1146 * undefined, for which there's an enclosing ifdef that
1147 * we're skipping...
1148 */
92490377 1149 skipIfLineno[skipIfLevel - 1] = lineno;
fbfaa208 1150 return (COND_SKIP);
984263bc
MD
1151 }
1152 } else if (skipLine) {
1153 /*
1154 * Don't even try to evaluate a conditional that's not an else if
1155 * we're skipping things...
1156 */
92490377 1157 skipIfLineno[skipIfLevel] = lineno;
984263bc 1158 skipIfLevel += 1;
fbfaa208 1159 return (COND_SKIP);
984263bc
MD
1160 }
1161
1162 /*
1163 * Initialize file-global variables for parsing
1164 */
1165 condDefProc = ifp->defProc;
1166 condInvert = ifp->doNot;
1167
1168 line += ifp->formlen;
1169
1170 while (*line == ' ' || *line == '\t') {
1171 line++;
1172 }
1173
1174 condExpr = line;
1175 condPushBack = None;
1176
1177 switch (CondE(TRUE)) {
1178 case True:
1179 if (CondToken(TRUE) == EndOfFile) {
1180 value = TRUE;
1181 break;
1182 }
1183 goto err;
1184 /*FALLTHRU*/
1185 case False:
1186 if (CondToken(TRUE) == EndOfFile) {
1187 value = FALSE;
1188 break;
1189 }
1190 /*FALLTHRU*/
1191 case Err:
1192 err:
fbfaa208 1193 Parse_Error(level, "Malformed conditional (%s)",
984263bc
MD
1194 line);
1195 return (COND_INVALID);
1196 default:
1197 break;
1198 }
1199 }
1200 if (!isElse) {
1201 condTop -= 1;
1202 } else if ((skipIfLevel != 0) || condStack[condTop]) {
1203 /*
1204 * If this is an else-type conditional, it should only take effect
1205 * if its corresponding if was evaluated and FALSE. If its if was
1206 * TRUE or skipped, we return COND_SKIP (and start skipping in case
1207 * we weren't already), leaving the stack unmolested so later elif's
1208 * don't screw up...
1209 */
1210 skipLine = TRUE;
1211 return (COND_SKIP);
1212 }
1213
1214 if (condTop < 0) {
1215 /*
1216 * This is the one case where we can definitely proclaim a fatal
1217 * error. If we don't, we're hosed.
1218 */
fbfaa208 1219 Parse_Error(PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
984263bc
MD
1220 return (COND_INVALID);
1221 } else {
1222 condStack[condTop] = value;
92490377 1223 condLineno[condTop] = lineno;
984263bc
MD
1224 skipLine = !value;
1225 return (value ? COND_PARSE : COND_SKIP);
1226 }
1227}
fbfaa208 1228
984263bc
MD
1229/*-
1230 *-----------------------------------------------------------------------
1231 * Cond_End --
1232 * Make sure everything's clean at the end of a makefile.
1233 *
1234 * Results:
1235 * None.
1236 *
1237 * Side Effects:
1238 * Parse_Error will be called if open conditionals are around.
1239 *
1240 *-----------------------------------------------------------------------
1241 */
1242void
84de9e23 1243Cond_End(void)
984263bc 1244{
92490377
JS
1245 int level;
1246
984263bc 1247 if (condTop != MAXIF) {
92490377
JS
1248 Parse_Error(PARSE_FATAL, "%d open conditional%s:",
1249 MAXIF - condTop + skipIfLevel,
1250 MAXIF - condTop + skipIfLevel== 1 ? "" : "s");
1251
1252 for (level = skipIfLevel; level > 0; level--)
1253 Parse_Error(PARSE_FATAL, "\t%*sat line %d (skipped)",
1254 MAXIF - condTop + level + 1, "", skipIfLineno[level - 1]);
1255 for (level = condTop; level < MAXIF; level++)
1256 Parse_Error(PARSE_FATAL, "\t%*sat line %d "
1257 "(evaluated to %s)", MAXIF - level + skipIfLevel, "",
1258 condLineno[level], condStack[level] ? "true" : "false");
984263bc
MD
1259 }
1260 condTop = MAXIF;
1261}