Annotation of src/usr.bin/make/cond.c, Revision 1.2
1.2 ! deraadt 1: /* $OpenBSD: cond.c,v 1.6 1995/06/14 15:18:58 christos Exp $ */
1.1 deraadt 2: /* $NetBSD: cond.c,v 1.6 1995/06/14 15:18:58 christos Exp $ */
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
44: static char sccsid[] = "@(#)cond.c 5.6 (Berkeley) 6/1/90";
45: #else
1.2 ! deraadt 46: static char rcsid[] = "$OpenBSD: cond.c,v 1.6 1995/06/14 15:18:58 christos 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: */
104: static int CondGetArg __P((char **, char **, char *, Boolean));
105: static Boolean CondDoDefined __P((int, char *));
106: static int CondStrMatch __P((ClientData, ClientData));
107: static Boolean CondDoMake __P((int, char *));
108: static Boolean CondDoExists __P((int, char *));
109: static Boolean CondDoTarget __P((int, char *));
110: static Boolean CondCvtArg __P((char *, double *));
111: static Token CondToken __P((Boolean));
112: static Token CondT __P((Boolean));
113: static Token CondF __P((Boolean));
114: static Token CondE __P((Boolean));
115:
116: static struct If {
117: char *form; /* Form of if */
118: int formlen; /* Length of form */
119: Boolean doNot; /* TRUE if default function should be negated */
120: Boolean (*defProc)(); /* Default function to apply */
121: } ifs[] = {
122: { "ifdef", 5, FALSE, CondDoDefined },
123: { "ifndef", 6, TRUE, CondDoDefined },
124: { "ifmake", 6, FALSE, CondDoMake },
125: { "ifnmake", 7, TRUE, CondDoMake },
126: { "if", 2, FALSE, CondDoDefined },
127: { (char *)0, 0, FALSE, (Boolean (*)())0 }
128: };
129:
130: static Boolean condInvert; /* Invert the default function */
131: static Boolean (*condDefProc)(); /* Default function to apply */
132: static char *condExpr; /* The expression to parse */
133: static Token condPushBack=None; /* Single push-back token used in
134: * parsing */
135:
136: #define MAXIF 30 /* greatest depth of #if'ing */
137:
138: static Boolean condStack[MAXIF]; /* Stack of conditionals's values */
139: static int condTop = MAXIF; /* Top-most conditional */
140: static int skipIfLevel=0; /* Depth of skipped conditionals */
141: static Boolean skipLine = FALSE; /* Whether the parse module is skipping
142: * lines */
143:
144: /*-
145: *-----------------------------------------------------------------------
146: * CondPushBack --
147: * Push back the most recent token read. We only need one level of
148: * this, so the thing is just stored in 'condPushback'.
149: *
150: * Results:
151: * None.
152: *
153: * Side Effects:
154: * condPushback is overwritten.
155: *
156: *-----------------------------------------------------------------------
157: */
158: static void
159: CondPushBack (t)
160: Token t; /* Token to push back into the "stream" */
161: {
162: condPushBack = t;
163: }
164:
165: /*-
166: *-----------------------------------------------------------------------
167: * CondGetArg --
168: * Find the argument of a built-in function.
169: *
170: * Results:
171: * The length of the argument and the address of the argument.
172: *
173: * Side Effects:
174: * The pointer is set to point to the closing parenthesis of the
175: * function call.
176: *
177: *-----------------------------------------------------------------------
178: */
179: static int
180: CondGetArg (linePtr, argPtr, func, parens)
181: char **linePtr;
182: char **argPtr;
183: char *func;
184: Boolean parens; /* TRUE if arg should be bounded by parens */
185: {
186: register char *cp;
187: int argLen;
188: register Buffer buf;
189:
190: cp = *linePtr;
191: if (parens) {
192: while (*cp != '(' && *cp != '\0') {
193: cp++;
194: }
195: if (*cp == '(') {
196: cp++;
197: }
198: }
199:
200: if (*cp == '\0') {
201: /*
202: * No arguments whatsoever. Because 'make' and 'defined' aren't really
203: * "reserved words", we don't print a message. I think this is better
204: * than hitting the user with a warning message every time s/he uses
205: * the word 'make' or 'defined' at the beginning of a symbol...
206: */
207: *argPtr = cp;
208: return (0);
209: }
210:
211: while (*cp == ' ' || *cp == '\t') {
212: cp++;
213: }
214:
215: /*
216: * Create a buffer for the argument and start it out at 16 characters
217: * long. Why 16? Why not?
218: */
219: buf = Buf_Init(16);
220:
221: while ((strchr(" \t)&|", *cp) == (char *)NULL) && (*cp != '\0')) {
222: if (*cp == '$') {
223: /*
224: * Parse the variable spec and install it as part of the argument
225: * if it's valid. We tell Var_Parse to complain on an undefined
226: * variable, so we don't do it too. Nor do we return an error,
227: * though perhaps we should...
228: */
229: char *cp2;
230: int len;
231: Boolean doFree;
232:
233: cp2 = Var_Parse(cp, VAR_CMD, TRUE, &len, &doFree);
234:
235: Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
236: if (doFree) {
237: free(cp2);
238: }
239: cp += len;
240: } else {
241: Buf_AddByte(buf, (Byte)*cp);
242: cp++;
243: }
244: }
245:
246: Buf_AddByte(buf, (Byte)'\0');
247: *argPtr = (char *)Buf_GetAll(buf, &argLen);
248: Buf_Destroy(buf, FALSE);
249:
250: while (*cp == ' ' || *cp == '\t') {
251: cp++;
252: }
253: if (parens && *cp != ')') {
254: Parse_Error (PARSE_WARNING, "Missing closing parenthesis for %s()",
255: func);
256: return (0);
257: } else if (parens) {
258: /*
259: * Advance pointer past close parenthesis.
260: */
261: cp++;
262: }
263:
264: *linePtr = cp;
265: return (argLen);
266: }
267:
268: /*-
269: *-----------------------------------------------------------------------
270: * CondDoDefined --
271: * Handle the 'defined' function for conditionals.
272: *
273: * Results:
274: * TRUE if the given variable is defined.
275: *
276: * Side Effects:
277: * None.
278: *
279: *-----------------------------------------------------------------------
280: */
281: static Boolean
282: CondDoDefined (argLen, arg)
283: int argLen;
284: char *arg;
285: {
286: char savec = arg[argLen];
287: char *p1;
288: Boolean result;
289:
290: arg[argLen] = '\0';
291: if (Var_Value (arg, VAR_CMD, &p1) != (char *)NULL) {
292: result = TRUE;
293: } else {
294: result = FALSE;
295: }
296: if (p1)
297: free(p1);
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)
339: int argLen;
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)
370: int argLen;
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
403: CondDoTarget (argLen, arg)
404: int argLen;
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.
437: *
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: char *cp;
549:
550: buf = Buf_Init(0);
551:
552: for (cp = lhs; *cp; cp++)
553: Buf_AddByte(buf, (Byte)*cp);
554:
555: if (doFree)
556: free(lhs);
557:
558: for (;*condExpr && !isspace((unsigned char) *condExpr);
559: condExpr++)
560: Buf_AddByte(buf, (Byte)*condExpr);
561:
562: Buf_AddByte(buf, (Byte)'\0');
563: lhs = (char *)Buf_GetAll(buf, &varSpecLen);
564: Buf_Destroy(buf, FALSE);
565:
566: doFree = TRUE;
567: }
568:
569: /*
570: * Skip whitespace to get to the operator
571: */
572: while (isspace((unsigned char) *condExpr))
573: condExpr++;
574:
575: /*
576: * Make sure the operator is a valid one. If it isn't a
577: * known relational operator, pretend we got a
578: * != 0 comparison.
579: */
580: op = condExpr;
581: switch (*condExpr) {
582: case '!':
583: case '=':
584: case '<':
585: case '>':
586: if (condExpr[1] == '=') {
587: condExpr += 2;
588: } else {
589: condExpr += 1;
590: }
591: break;
592: default:
593: op = "!=";
594: rhs = "0";
595:
596: goto do_compare;
597: }
598: while (isspace((unsigned char) *condExpr)) {
599: condExpr++;
600: }
601: if (*condExpr == '\0') {
602: Parse_Error(PARSE_WARNING,
603: "Missing right-hand-side of operator");
604: goto error;
605: }
606: rhs = condExpr;
607: do_compare:
608: if (*rhs == '"') {
609: /*
610: * Doing a string comparison. Only allow == and != for
611: * operators.
612: */
613: char *string;
614: char *cp, *cp2;
615: int qt;
616: Buffer buf;
617:
618: do_string_compare:
619: if (((*op != '!') && (*op != '=')) || (op[1] != '=')) {
620: Parse_Error(PARSE_WARNING,
621: "String comparison operator should be either == or !=");
622: goto error;
623: }
624:
625: buf = Buf_Init(0);
626: qt = *rhs == '"' ? 1 : 0;
627:
628: for (cp = &rhs[qt];
629: ((qt && (*cp != '"')) ||
630: (!qt && strchr(" \t)", *cp) == NULL)) &&
631: (*cp != '\0'); cp++) {
632: if ((*cp == '\\') && (cp[1] != '\0')) {
633: /*
634: * Backslash escapes things -- skip over next
635: * character, if it exists.
636: */
637: cp++;
638: Buf_AddByte(buf, (Byte)*cp);
639: } else if (*cp == '$') {
640: int len;
641: Boolean freeIt;
642:
643: cp2 = Var_Parse(cp, VAR_CMD, doEval,&len, &freeIt);
644: if (cp2 != var_Error) {
645: Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
646: if (freeIt) {
647: free(cp2);
648: }
649: cp += len - 1;
650: } else {
651: Buf_AddByte(buf, (Byte)*cp);
652: }
653: } else {
654: Buf_AddByte(buf, (Byte)*cp);
655: }
656: }
657:
658: Buf_AddByte(buf, (Byte)0);
659:
660: string = (char *)Buf_GetAll(buf, (int *)0);
661: Buf_Destroy(buf, FALSE);
662:
663: if (DEBUG(COND)) {
664: printf("lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
665: lhs, string, op);
666: }
667: /*
668: * Null-terminate rhs and perform the comparison.
669: * t is set to the result.
670: */
671: if (*op == '=') {
672: t = strcmp(lhs, string) ? False : True;
673: } else {
674: t = strcmp(lhs, string) ? True : False;
675: }
676: free(string);
677: if (rhs == condExpr) {
678: if (!qt && *cp == ')')
679: condExpr = cp;
680: else
681: condExpr = cp + 1;
682: }
683: } else {
684: /*
685: * rhs is either a float or an integer. Convert both the
686: * lhs and the rhs to a double and compare the two.
687: */
688: double left, right;
689: char *string;
690:
691: if (!CondCvtArg(lhs, &left))
692: goto do_string_compare;
693: if (*rhs == '$') {
694: int len;
695: Boolean freeIt;
696:
697: string = Var_Parse(rhs, VAR_CMD, doEval,&len,&freeIt);
698: if (string == var_Error) {
699: right = 0.0;
700: } else {
701: if (!CondCvtArg(string, &right)) {
702: if (freeIt)
703: free(string);
704: goto do_string_compare;
705: }
706: if (freeIt)
707: free(string);
708: if (rhs == condExpr)
709: condExpr += len;
710: }
711: } else {
712: if (!CondCvtArg(rhs, &right))
713: goto do_string_compare;
714: if (rhs == condExpr) {
715: /*
716: * Skip over the right-hand side
717: */
718: while(!isspace((unsigned char) *condExpr) &&
719: (*condExpr != '\0')) {
720: condExpr++;
721: }
722: }
723: }
724:
725: if (DEBUG(COND)) {
726: printf("left = %f, right = %f, op = %.2s\n", left,
727: right, op);
728: }
729: switch(op[0]) {
730: case '!':
731: if (op[1] != '=') {
732: Parse_Error(PARSE_WARNING,
733: "Unknown operator");
734: goto error;
735: }
736: t = (left != right ? True : False);
737: break;
738: case '=':
739: if (op[1] != '=') {
740: Parse_Error(PARSE_WARNING,
741: "Unknown operator");
742: goto error;
743: }
744: t = (left == right ? True : False);
745: break;
746: case '<':
747: if (op[1] == '=') {
748: t = (left <= right ? True : False);
749: } else {
750: t = (left < right ? True : False);
751: }
752: break;
753: case '>':
754: if (op[1] == '=') {
755: t = (left >= right ? True : False);
756: } else {
757: t = (left > right ? True : False);
758: }
759: break;
760: }
761: }
762: error:
763: if (doFree)
764: free(lhs);
765: break;
766: }
767: default: {
768: Boolean (*evalProc)();
769: Boolean invert = FALSE;
770: char *arg;
771: int arglen;
772:
773: if (strncmp (condExpr, "defined", 7) == 0) {
774: /*
775: * Use CondDoDefined to evaluate the argument and
776: * CondGetArg to extract the argument from the 'function
777: * call'.
778: */
779: evalProc = CondDoDefined;
780: condExpr += 7;
781: arglen = CondGetArg (&condExpr, &arg, "defined", TRUE);
782: if (arglen == 0) {
783: condExpr -= 7;
784: goto use_default;
785: }
786: } else if (strncmp (condExpr, "make", 4) == 0) {
787: /*
788: * Use CondDoMake to evaluate the argument and
789: * CondGetArg to extract the argument from the 'function
790: * call'.
791: */
792: evalProc = CondDoMake;
793: condExpr += 4;
794: arglen = CondGetArg (&condExpr, &arg, "make", TRUE);
795: if (arglen == 0) {
796: condExpr -= 4;
797: goto use_default;
798: }
799: } else if (strncmp (condExpr, "exists", 6) == 0) {
800: /*
801: * Use CondDoExists to evaluate the argument and
802: * CondGetArg to extract the argument from the
803: * 'function call'.
804: */
805: evalProc = CondDoExists;
806: condExpr += 6;
807: arglen = CondGetArg(&condExpr, &arg, "exists", TRUE);
808: if (arglen == 0) {
809: condExpr -= 6;
810: goto use_default;
811: }
812: } else if (strncmp(condExpr, "empty", 5) == 0) {
813: /*
814: * Use Var_Parse to parse the spec in parens and return
815: * True if the resulting string is empty.
816: */
817: int length;
818: Boolean doFree;
819: char *val;
820:
821: condExpr += 5;
822:
823: for (arglen = 0;
824: condExpr[arglen] != '(' && condExpr[arglen] != '\0';
825: arglen += 1)
826: continue;
827:
828: if (condExpr[arglen] != '\0') {
829: val = Var_Parse(&condExpr[arglen - 1], VAR_CMD,
830: doEval, &length, &doFree);
831: if (val == var_Error) {
832: t = Err;
833: } else {
834: /*
835: * A variable is empty when it just contains
836: * spaces... 4/15/92, christos
837: */
838: char *p;
839: for (p = val; *p && isspace((unsigned char)*p); p++)
840: continue;
841: t = (*p == '\0') ? True : False;
842: }
843: if (doFree) {
844: free(val);
845: }
846: /*
847: * Advance condExpr to beyond the closing ). Note that
848: * we subtract one from arglen + length b/c length
849: * is calculated from condExpr[arglen - 1].
850: */
851: condExpr += arglen + length - 1;
852: } else {
853: condExpr -= 5;
854: goto use_default;
855: }
856: break;
857: } else if (strncmp (condExpr, "target", 6) == 0) {
858: /*
859: * Use CondDoTarget to evaluate the argument and
860: * CondGetArg to extract the argument from the
861: * 'function call'.
862: */
863: evalProc = CondDoTarget;
864: condExpr += 6;
865: arglen = CondGetArg(&condExpr, &arg, "target", TRUE);
866: if (arglen == 0) {
867: condExpr -= 6;
868: goto use_default;
869: }
870: } else {
871: /*
872: * The symbol is itself the argument to the default
873: * function. We advance condExpr to the end of the symbol
874: * by hand (the next whitespace, closing paren or
875: * binary operator) and set to invert the evaluation
876: * function if condInvert is TRUE.
877: */
878: use_default:
879: invert = condInvert;
880: evalProc = condDefProc;
881: arglen = CondGetArg(&condExpr, &arg, "", FALSE);
882: }
883:
884: /*
885: * Evaluate the argument using the set function. If invert
886: * is TRUE, we invert the sense of the function.
887: */
888: t = (!doEval || (* evalProc) (arglen, arg) ?
889: (invert ? False : True) :
890: (invert ? True : False));
891: free(arg);
892: break;
893: }
894: }
895: } else {
896: t = condPushBack;
897: condPushBack = None;
898: }
899: return (t);
900: }
901:
902: /*-
903: *-----------------------------------------------------------------------
904: * CondT --
905: * Parse a single term in the expression. This consists of a terminal
906: * symbol or Not and a terminal symbol (not including the binary
907: * operators):
908: * T -> defined(variable) | make(target) | exists(file) | symbol
909: * T -> ! T | ( E )
910: *
911: * Results:
912: * True, False or Err.
913: *
914: * Side Effects:
915: * Tokens are consumed.
916: *
917: *-----------------------------------------------------------------------
918: */
919: static Token
920: CondT(doEval)
921: Boolean doEval;
922: {
923: Token t;
924:
925: t = CondToken(doEval);
926:
927: if (t == EndOfFile) {
928: /*
929: * If we reached the end of the expression, the expression
930: * is malformed...
931: */
932: t = Err;
933: } else if (t == LParen) {
934: /*
935: * T -> ( E )
936: */
937: t = CondE(doEval);
938: if (t != Err) {
939: if (CondToken(doEval) != RParen) {
940: t = Err;
941: }
942: }
943: } else if (t == Not) {
944: t = CondT(doEval);
945: if (t == True) {
946: t = False;
947: } else if (t == False) {
948: t = True;
949: }
950: }
951: return (t);
952: }
953:
954: /*-
955: *-----------------------------------------------------------------------
956: * CondF --
957: * Parse a conjunctive factor (nice name, wot?)
958: * F -> T && F | T
959: *
960: * Results:
961: * True, False or Err
962: *
963: * Side Effects:
964: * Tokens are consumed.
965: *
966: *-----------------------------------------------------------------------
967: */
968: static Token
969: CondF(doEval)
970: Boolean doEval;
971: {
972: Token l, o;
973:
974: l = CondT(doEval);
975: if (l != Err) {
976: o = CondToken(doEval);
977:
978: if (o == And) {
979: /*
980: * F -> T && F
981: *
982: * If T is False, the whole thing will be False, but we have to
983: * parse the r.h.s. anyway (to throw it away).
984: * If T is True, the result is the r.h.s., be it an Err or no.
985: */
986: if (l == True) {
987: l = CondF(doEval);
988: } else {
989: (void) CondF(FALSE);
990: }
991: } else {
992: /*
993: * F -> T
994: */
995: CondPushBack (o);
996: }
997: }
998: return (l);
999: }
1000:
1001: /*-
1002: *-----------------------------------------------------------------------
1003: * CondE --
1004: * Main expression production.
1005: * E -> F || E | F
1006: *
1007: * Results:
1008: * True, False or Err.
1009: *
1010: * Side Effects:
1011: * Tokens are, of course, consumed.
1012: *
1013: *-----------------------------------------------------------------------
1014: */
1015: static Token
1016: CondE(doEval)
1017: Boolean doEval;
1018: {
1019: Token l, o;
1020:
1021: l = CondF(doEval);
1022: if (l != Err) {
1023: o = CondToken(doEval);
1024:
1025: if (o == Or) {
1026: /*
1027: * E -> F || E
1028: *
1029: * A similar thing occurs for ||, except that here we make sure
1030: * the l.h.s. is False before we bother to evaluate the r.h.s.
1031: * Once again, if l is False, the result is the r.h.s. and once
1032: * again if l is True, we parse the r.h.s. to throw it away.
1033: */
1034: if (l == False) {
1035: l = CondE(doEval);
1036: } else {
1037: (void) CondE(FALSE);
1038: }
1039: } else {
1040: /*
1041: * E -> F
1042: */
1043: CondPushBack (o);
1044: }
1045: }
1046: return (l);
1047: }
1048:
1049: /*-
1050: *-----------------------------------------------------------------------
1051: * Cond_Eval --
1052: * Evaluate the conditional in the passed line. The line
1053: * looks like this:
1054: * #<cond-type> <expr>
1055: * where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1056: * ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1057: * and <expr> consists of &&, ||, !, make(target), defined(variable)
1058: * and parenthetical groupings thereof.
1059: *
1060: * Results:
1061: * COND_PARSE if should parse lines after the conditional
1062: * COND_SKIP if should skip lines after the conditional
1063: * COND_INVALID if not a valid conditional.
1064: *
1065: * Side Effects:
1066: * None.
1067: *
1068: *-----------------------------------------------------------------------
1069: */
1070: int
1071: Cond_Eval (line)
1072: char *line; /* Line to parse */
1073: {
1074: struct If *ifp;
1075: Boolean isElse;
1076: Boolean value = FALSE;
1077: int level; /* Level at which to report errors. */
1078:
1079: level = PARSE_FATAL;
1080:
1081: for (line++; *line == ' ' || *line == '\t'; line++) {
1082: continue;
1083: }
1084:
1085: /*
1086: * Find what type of if we're dealing with. The result is left
1087: * in ifp and isElse is set TRUE if it's an elif line.
1088: */
1089: if (line[0] == 'e' && line[1] == 'l') {
1090: line += 2;
1091: isElse = TRUE;
1092: } else if (strncmp (line, "endif", 5) == 0) {
1093: /*
1094: * End of a conditional section. If skipIfLevel is non-zero, that
1095: * conditional was skipped, so lines following it should also be
1096: * skipped. Hence, we return COND_SKIP. Otherwise, the conditional
1097: * was read so succeeding lines should be parsed (think about it...)
1098: * so we return COND_PARSE, unless this endif isn't paired with
1099: * a decent if.
1100: */
1101: if (skipIfLevel != 0) {
1102: skipIfLevel -= 1;
1103: return (COND_SKIP);
1104: } else {
1105: if (condTop == MAXIF) {
1106: Parse_Error (level, "if-less endif");
1107: return (COND_INVALID);
1108: } else {
1109: skipLine = FALSE;
1110: condTop += 1;
1111: return (COND_PARSE);
1112: }
1113: }
1114: } else {
1115: isElse = FALSE;
1116: }
1117:
1118: /*
1119: * Figure out what sort of conditional it is -- what its default
1120: * function is, etc. -- by looking in the table of valid "ifs"
1121: */
1122: for (ifp = ifs; ifp->form != (char *)0; ifp++) {
1123: if (strncmp (ifp->form, line, ifp->formlen) == 0) {
1124: break;
1125: }
1126: }
1127:
1128: if (ifp->form == (char *) 0) {
1129: /*
1130: * Nothing fit. If the first word on the line is actually
1131: * "else", it's a valid conditional whose value is the inverse
1132: * of the previous if we parsed.
1133: */
1134: if (isElse && (line[0] == 's') && (line[1] == 'e')) {
1135: if (condTop == MAXIF) {
1136: Parse_Error (level, "if-less else");
1137: return (COND_INVALID);
1138: } else if (skipIfLevel == 0) {
1139: value = !condStack[condTop];
1140: } else {
1141: return (COND_SKIP);
1142: }
1143: } else {
1144: /*
1145: * Not a valid conditional type. No error...
1146: */
1147: return (COND_INVALID);
1148: }
1149: } else {
1150: if (isElse) {
1151: if (condTop == MAXIF) {
1152: Parse_Error (level, "if-less elif");
1153: return (COND_INVALID);
1154: } else if (skipIfLevel != 0) {
1155: /*
1156: * If skipping this conditional, just ignore the whole thing.
1157: * If we don't, the user might be employing a variable that's
1158: * undefined, for which there's an enclosing ifdef that
1159: * we're skipping...
1160: */
1161: return(COND_SKIP);
1162: }
1163: } else if (skipLine) {
1164: /*
1165: * Don't even try to evaluate a conditional that's not an else if
1166: * we're skipping things...
1167: */
1168: skipIfLevel += 1;
1169: return(COND_SKIP);
1170: }
1171:
1172: /*
1173: * Initialize file-global variables for parsing
1174: */
1175: condDefProc = ifp->defProc;
1176: condInvert = ifp->doNot;
1177:
1178: line += ifp->formlen;
1179:
1180: while (*line == ' ' || *line == '\t') {
1181: line++;
1182: }
1183:
1184: condExpr = line;
1185: condPushBack = None;
1186:
1187: switch (CondE(TRUE)) {
1188: case True:
1189: if (CondToken(TRUE) == EndOfFile) {
1190: value = TRUE;
1191: break;
1192: }
1193: goto err;
1194: /*FALLTHRU*/
1195: case False:
1196: if (CondToken(TRUE) == EndOfFile) {
1197: value = FALSE;
1198: break;
1199: }
1200: /*FALLTHRU*/
1201: case Err:
1202: err:
1203: Parse_Error (level, "Malformed conditional (%s)",
1204: line);
1205: return (COND_INVALID);
1206: default:
1207: break;
1208: }
1209: }
1210: if (!isElse) {
1211: condTop -= 1;
1212: } else if ((skipIfLevel != 0) || condStack[condTop]) {
1213: /*
1214: * If this is an else-type conditional, it should only take effect
1215: * if its corresponding if was evaluated and FALSE. If its if was
1216: * TRUE or skipped, we return COND_SKIP (and start skipping in case
1217: * we weren't already), leaving the stack unmolested so later elif's
1218: * don't screw up...
1219: */
1220: skipLine = TRUE;
1221: return (COND_SKIP);
1222: }
1223:
1224: if (condTop < 0) {
1225: /*
1226: * This is the one case where we can definitely proclaim a fatal
1227: * error. If we don't, we're hosed.
1228: */
1229: Parse_Error (PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
1230: return (COND_INVALID);
1231: } else {
1232: condStack[condTop] = value;
1233: skipLine = !value;
1234: return (value ? COND_PARSE : COND_SKIP);
1235: }
1236: }
1237:
1238: /*-
1239: *-----------------------------------------------------------------------
1240: * Cond_End --
1241: * Make sure everything's clean at the end of a makefile.
1242: *
1243: * Results:
1244: * None.
1245: *
1246: * Side Effects:
1247: * Parse_Error will be called if open conditionals are around.
1248: *
1249: *-----------------------------------------------------------------------
1250: */
1251: void
1252: Cond_End()
1253: {
1254: if (condTop != MAXIF) {
1255: Parse_Error(PARSE_FATAL, "%d open conditional%s", MAXIF-condTop,
1256: MAXIF-condTop == 1 ? "" : "s");
1257: }
1258: condTop = MAXIF;
1259: }