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