Annotation of src/usr.bin/make/cond.c, Revision 1.6
1.6 ! espie 1: /* $OpenBSD: cond.c,v 1.5 1999/12/06 22:24:31 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.6 ! espie 46: static char rcsid[] = "$OpenBSD: cond.c,v 1.5 1999/12/06 22:24:31 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.5 espie 237: Buf_AddChars(buf, strlen(cp2), 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.5 espie 248: Buf_AddChar(buf, '\0');
249: *argPtr = Buf_GetAll(buf, &argLen);
1.1 deraadt 250: Buf_Destroy(buf, FALSE);
251:
252: while (*cp == ' ' || *cp == '\t') {
253: cp++;
254: }
255: if (parens && *cp != ')') {
256: Parse_Error (PARSE_WARNING, "Missing closing parenthesis for %s()",
257: func);
258: return (0);
259: } else if (parens) {
260: /*
261: * Advance pointer past close parenthesis.
262: */
263: cp++;
264: }
1.3 millert 265:
1.1 deraadt 266: *linePtr = cp;
267: return (argLen);
268: }
269:
270: /*-
271: *-----------------------------------------------------------------------
272: * CondDoDefined --
273: * Handle the 'defined' function for conditionals.
274: *
275: * Results:
276: * TRUE if the given variable is defined.
277: *
278: * Side Effects:
279: * None.
280: *
281: *-----------------------------------------------------------------------
282: */
283: static Boolean
1.5 espie 284: CondDoDefined(argLen, arg)
285: size_t argLen;
1.1 deraadt 286: char *arg;
287: {
288: char savec = arg[argLen];
289: Boolean result;
290:
291: arg[argLen] = '\0';
1.6 ! espie 292: if (Var_Value(arg, VAR_CMD) != NULL)
1.1 deraadt 293: result = TRUE;
1.6 ! espie 294: else
1.1 deraadt 295: result = FALSE;
296: arg[argLen] = savec;
297: return (result);
298: }
299:
300: /*-
301: *-----------------------------------------------------------------------
302: * CondStrMatch --
303: * Front-end for Str_Match so it returns 0 on match and non-zero
304: * on mismatch. Callback function for CondDoMake via Lst_Find
305: *
306: * Results:
307: * 0 if string matches pattern
308: *
309: * Side Effects:
310: * None
311: *
312: *-----------------------------------------------------------------------
313: */
314: static int
315: CondStrMatch(string, pattern)
316: ClientData string;
317: ClientData pattern;
318: {
319: return(!Str_Match((char *) string,(char *) pattern));
320: }
321:
322: /*-
323: *-----------------------------------------------------------------------
324: * CondDoMake --
325: * Handle the 'make' function for conditionals.
326: *
327: * Results:
328: * TRUE if the given target is being made.
329: *
330: * Side Effects:
331: * None.
332: *
333: *-----------------------------------------------------------------------
334: */
335: static Boolean
336: CondDoMake (argLen, arg)
1.5 espie 337: size_t argLen;
1.1 deraadt 338: char *arg;
339: {
340: char savec = arg[argLen];
341: Boolean result;
342:
343: arg[argLen] = '\0';
344: if (Lst_Find (create, (ClientData)arg, CondStrMatch) == NILLNODE) {
345: result = FALSE;
346: } else {
347: result = TRUE;
348: }
349: arg[argLen] = savec;
350: return (result);
351: }
352:
353: /*-
354: *-----------------------------------------------------------------------
355: * CondDoExists --
356: * See if the given file exists.
357: *
358: * Results:
359: * TRUE if the file exists and FALSE if it does not.
360: *
361: * Side Effects:
362: * None.
363: *
364: *-----------------------------------------------------------------------
365: */
366: static Boolean
367: CondDoExists (argLen, arg)
1.5 espie 368: size_t argLen;
1.1 deraadt 369: char *arg;
370: {
371: char savec = arg[argLen];
372: Boolean result;
373: char *path;
374:
375: arg[argLen] = '\0';
376: path = Dir_FindFile(arg, dirSearchPath);
377: if (path != (char *)NULL) {
378: result = TRUE;
379: free(path);
380: } else {
381: result = FALSE;
382: }
383: arg[argLen] = savec;
384: return (result);
385: }
386:
387: /*-
388: *-----------------------------------------------------------------------
389: * CondDoTarget --
390: * See if the given node exists and is an actual target.
391: *
392: * Results:
393: * TRUE if the node exists as a target and FALSE if it does not.
394: *
395: * Side Effects:
396: * None.
397: *
398: *-----------------------------------------------------------------------
399: */
400: static Boolean
1.5 espie 401: CondDoTarget(argLen, arg)
402: size_t argLen;
1.1 deraadt 403: char *arg;
404: {
405: char savec = arg[argLen];
406: Boolean result;
407: GNode *gn;
408:
409: arg[argLen] = '\0';
410: gn = Targ_FindNode(arg, TARG_NOCREATE);
411: if ((gn != NILGNODE) && !OP_NOP(gn->type)) {
412: result = TRUE;
413: } else {
414: result = FALSE;
415: }
416: arg[argLen] = savec;
417: return (result);
418: }
419:
420:
421: /*-
422: *-----------------------------------------------------------------------
423: * CondCvtArg --
424: * Convert the given number into a double. If the number begins
425: * with 0x, it is interpreted as a hexadecimal integer
426: * and converted to a double from there. All other strings just have
427: * strtod called on them.
428: *
429: * Results:
430: * Sets 'value' to double value of string.
431: * Returns true if the string was a valid number, false o.w.
432: *
433: * Side Effects:
434: * Can change 'value' even if string is not a valid number.
1.3 millert 435: *
1.1 deraadt 436: *
437: *-----------------------------------------------------------------------
438: */
439: static Boolean
440: CondCvtArg(str, value)
441: register char *str;
442: double *value;
443: {
444: if ((*str == '0') && (str[1] == 'x')) {
445: register long i;
446:
447: for (str += 2, i = 0; *str; str++) {
448: int x;
449: if (isdigit((unsigned char) *str))
450: x = *str - '0';
451: else if (isxdigit((unsigned char) *str))
452: x = 10 + *str - isupper((unsigned char) *str) ? 'A' : 'a';
453: else
454: return FALSE;
455: i = (i << 4) + x;
456: }
457: *value = (double) i;
458: return TRUE;
459: }
460: else {
461: char *eptr;
462: *value = strtod(str, &eptr);
463: return *eptr == '\0';
464: }
465: }
466:
467: /*-
468: *-----------------------------------------------------------------------
469: * CondToken --
470: * Return the next token from the input.
471: *
472: * Results:
473: * A Token for the next lexical token in the stream.
474: *
475: * Side Effects:
476: * condPushback will be set back to None if it is used.
477: *
478: *-----------------------------------------------------------------------
479: */
480: static Token
481: CondToken(doEval)
482: Boolean doEval;
483: {
484: Token t;
485:
486: if (condPushBack == None) {
487: while (*condExpr == ' ' || *condExpr == '\t') {
488: condExpr++;
489: }
490: switch (*condExpr) {
491: case '(':
492: t = LParen;
493: condExpr++;
494: break;
495: case ')':
496: t = RParen;
497: condExpr++;
498: break;
499: case '|':
500: if (condExpr[1] == '|') {
501: condExpr++;
502: }
503: condExpr++;
504: t = Or;
505: break;
506: case '&':
507: if (condExpr[1] == '&') {
508: condExpr++;
509: }
510: condExpr++;
511: t = And;
512: break;
513: case '!':
514: t = Not;
515: condExpr++;
516: break;
517: case '\n':
518: case '\0':
519: t = EndOfFile;
520: break;
521: case '$': {
522: char *lhs;
523: char *rhs;
524: char *op;
525: int varSpecLen;
526: Boolean doFree;
527:
528: /*
529: * Parse the variable spec and skip over it, saving its
530: * value in lhs.
531: */
532: t = Err;
533: lhs = Var_Parse(condExpr, VAR_CMD, doEval,&varSpecLen,&doFree);
534: if (lhs == var_Error) {
535: /*
536: * Even if !doEval, we still report syntax errors, which
537: * is what getting var_Error back with !doEval means.
538: */
539: return(Err);
540: }
541: condExpr += varSpecLen;
542:
543: if (!isspace((unsigned char) *condExpr) &&
544: strchr("!=><", *condExpr) == NULL) {
545: Buffer buf;
546: char *cp;
547:
548: buf = Buf_Init(0);
549:
550: for (cp = lhs; *cp; cp++)
1.5 espie 551: Buf_AddChar(buf, *cp);
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.5 espie 560: Buf_AddChar(buf, '\0');
561: lhs = Buf_GetAll(buf, &varSpecLen);
1.1 deraadt 562: Buf_Destroy(buf, FALSE);
563:
564: doFree = TRUE;
565: }
566:
567: /*
568: * Skip whitespace to get to the operator
569: */
570: while (isspace((unsigned char) *condExpr))
571: condExpr++;
572:
573: /*
574: * Make sure the operator is a valid one. If it isn't a
575: * known relational operator, pretend we got a
576: * != 0 comparison.
577: */
578: op = condExpr;
579: switch (*condExpr) {
580: case '!':
581: case '=':
582: case '<':
583: case '>':
584: if (condExpr[1] == '=') {
585: condExpr += 2;
586: } else {
587: condExpr += 1;
588: }
589: break;
590: default:
591: op = "!=";
592: rhs = "0";
593:
594: goto do_compare;
595: }
596: while (isspace((unsigned char) *condExpr)) {
597: condExpr++;
598: }
599: if (*condExpr == '\0') {
600: Parse_Error(PARSE_WARNING,
601: "Missing right-hand-side of operator");
602: goto error;
603: }
604: rhs = condExpr;
605: do_compare:
606: if (*rhs == '"') {
607: /*
608: * Doing a string comparison. Only allow == and != for
609: * operators.
610: */
611: char *string;
612: char *cp, *cp2;
613: int qt;
614: Buffer buf;
615:
616: do_string_compare:
617: if (((*op != '!') && (*op != '=')) || (op[1] != '=')) {
618: Parse_Error(PARSE_WARNING,
619: "String comparison operator should be either == or !=");
620: goto error;
621: }
622:
623: buf = Buf_Init(0);
624: qt = *rhs == '"' ? 1 : 0;
1.3 millert 625:
626: for (cp = &rhs[qt];
627: ((qt && (*cp != '"')) ||
628: (!qt && strchr(" \t)", *cp) == NULL)) &&
1.1 deraadt 629: (*cp != '\0'); cp++) {
630: if ((*cp == '\\') && (cp[1] != '\0')) {
631: /*
632: * Backslash escapes things -- skip over next
633: * character, if it exists.
634: */
635: cp++;
1.5 espie 636: Buf_AddChar(buf, *cp);
1.1 deraadt 637: } else if (*cp == '$') {
638: int len;
639: Boolean freeIt;
1.3 millert 640:
1.1 deraadt 641: cp2 = Var_Parse(cp, VAR_CMD, doEval,&len, &freeIt);
642: if (cp2 != var_Error) {
1.5 espie 643: Buf_AddChars(buf, strlen(cp2), cp2);
1.1 deraadt 644: if (freeIt) {
645: free(cp2);
646: }
647: cp += len - 1;
648: } else {
1.5 espie 649: Buf_AddChar(buf, *cp);
1.1 deraadt 650: }
651: } else {
1.5 espie 652: Buf_AddChar(buf, *cp);
1.1 deraadt 653: }
654: }
655:
1.5 espie 656: Buf_AddChar(buf, '\0');
1.1 deraadt 657:
1.5 espie 658: string = Buf_GetAll(buf, NULL);
1.1 deraadt 659: Buf_Destroy(buf, FALSE);
660:
661: if (DEBUG(COND)) {
662: printf("lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
663: lhs, string, op);
664: }
665: /*
666: * Null-terminate rhs and perform the comparison.
667: * t is set to the result.
668: */
669: if (*op == '=') {
670: t = strcmp(lhs, string) ? False : True;
671: } else {
672: t = strcmp(lhs, string) ? True : False;
673: }
674: free(string);
675: if (rhs == condExpr) {
676: if (!qt && *cp == ')')
677: condExpr = cp;
678: else
679: condExpr = cp + 1;
680: }
681: } else {
682: /*
683: * rhs is either a float or an integer. Convert both the
684: * lhs and the rhs to a double and compare the two.
685: */
686: double left, right;
687: char *string;
688:
689: if (!CondCvtArg(lhs, &left))
690: goto do_string_compare;
691: if (*rhs == '$') {
692: int len;
693: Boolean freeIt;
1.3 millert 694:
1.1 deraadt 695: string = Var_Parse(rhs, VAR_CMD, doEval,&len,&freeIt);
696: if (string == var_Error) {
697: right = 0.0;
698: } else {
699: if (!CondCvtArg(string, &right)) {
700: if (freeIt)
701: free(string);
702: goto do_string_compare;
703: }
704: if (freeIt)
705: free(string);
706: if (rhs == condExpr)
707: condExpr += len;
708: }
709: } else {
710: if (!CondCvtArg(rhs, &right))
711: goto do_string_compare;
712: if (rhs == condExpr) {
713: /*
714: * Skip over the right-hand side
715: */
716: while(!isspace((unsigned char) *condExpr) &&
717: (*condExpr != '\0')) {
718: condExpr++;
719: }
720: }
721: }
1.3 millert 722:
1.1 deraadt 723: if (DEBUG(COND)) {
724: printf("left = %f, right = %f, op = %.2s\n", left,
725: right, op);
726: }
727: switch(op[0]) {
728: case '!':
729: if (op[1] != '=') {
730: Parse_Error(PARSE_WARNING,
731: "Unknown operator");
732: goto error;
733: }
734: t = (left != right ? True : False);
735: break;
736: case '=':
737: if (op[1] != '=') {
738: Parse_Error(PARSE_WARNING,
739: "Unknown operator");
740: goto error;
741: }
742: t = (left == right ? True : False);
743: break;
744: case '<':
745: if (op[1] == '=') {
746: t = (left <= right ? True : False);
747: } else {
748: t = (left < right ? True : False);
749: }
750: break;
751: case '>':
752: if (op[1] == '=') {
753: t = (left >= right ? True : False);
754: } else {
755: t = (left > right ? True : False);
756: }
757: break;
758: }
759: }
760: error:
761: if (doFree)
762: free(lhs);
763: break;
764: }
765: default: {
1.5 espie 766: Boolean (*evalProc) __P((size_t, char *));
1.1 deraadt 767: Boolean invert = FALSE;
768: char *arg;
1.5 espie 769: size_t arglen;
1.3 millert 770:
1.1 deraadt 771: if (strncmp (condExpr, "defined", 7) == 0) {
772: /*
773: * Use CondDoDefined to evaluate the argument and
774: * CondGetArg to extract the argument from the 'function
775: * call'.
776: */
777: evalProc = CondDoDefined;
778: condExpr += 7;
779: arglen = CondGetArg (&condExpr, &arg, "defined", TRUE);
780: if (arglen == 0) {
781: condExpr -= 7;
782: goto use_default;
783: }
784: } else if (strncmp (condExpr, "make", 4) == 0) {
785: /*
786: * Use CondDoMake to evaluate the argument and
787: * CondGetArg to extract the argument from the 'function
788: * call'.
789: */
790: evalProc = CondDoMake;
791: condExpr += 4;
792: arglen = CondGetArg (&condExpr, &arg, "make", TRUE);
793: if (arglen == 0) {
794: condExpr -= 4;
795: goto use_default;
796: }
797: } else if (strncmp (condExpr, "exists", 6) == 0) {
798: /*
799: * Use CondDoExists to evaluate the argument and
800: * CondGetArg to extract the argument from the
801: * 'function call'.
802: */
803: evalProc = CondDoExists;
804: condExpr += 6;
805: arglen = CondGetArg(&condExpr, &arg, "exists", TRUE);
806: if (arglen == 0) {
807: condExpr -= 6;
808: goto use_default;
809: }
810: } else if (strncmp(condExpr, "empty", 5) == 0) {
811: /*
812: * Use Var_Parse to parse the spec in parens and return
813: * True if the resulting string is empty.
814: */
815: int length;
816: Boolean doFree;
817: char *val;
818:
819: condExpr += 5;
820:
821: for (arglen = 0;
822: condExpr[arglen] != '(' && condExpr[arglen] != '\0';
823: arglen += 1)
824: continue;
825:
826: if (condExpr[arglen] != '\0') {
827: val = Var_Parse(&condExpr[arglen - 1], VAR_CMD,
828: doEval, &length, &doFree);
829: if (val == var_Error) {
830: t = Err;
831: } else {
1.3 millert 832: /*
833: * A variable is empty when it just contains
1.1 deraadt 834: * spaces... 4/15/92, christos
835: */
836: char *p;
837: for (p = val; *p && isspace((unsigned char)*p); p++)
838: continue;
839: t = (*p == '\0') ? True : False;
840: }
841: if (doFree) {
842: free(val);
843: }
844: /*
845: * Advance condExpr to beyond the closing ). Note that
846: * we subtract one from arglen + length b/c length
847: * is calculated from condExpr[arglen - 1].
848: */
849: condExpr += arglen + length - 1;
850: } else {
851: condExpr -= 5;
852: goto use_default;
853: }
854: break;
855: } else if (strncmp (condExpr, "target", 6) == 0) {
856: /*
857: * Use CondDoTarget to evaluate the argument and
858: * CondGetArg to extract the argument from the
859: * 'function call'.
860: */
861: evalProc = CondDoTarget;
862: condExpr += 6;
863: arglen = CondGetArg(&condExpr, &arg, "target", TRUE);
864: if (arglen == 0) {
865: condExpr -= 6;
866: goto use_default;
867: }
868: } else {
869: /*
870: * The symbol is itself the argument to the default
871: * function. We advance condExpr to the end of the symbol
872: * by hand (the next whitespace, closing paren or
873: * binary operator) and set to invert the evaluation
874: * function if condInvert is TRUE.
875: */
876: use_default:
877: invert = condInvert;
878: evalProc = condDefProc;
879: arglen = CondGetArg(&condExpr, &arg, "", FALSE);
880: }
881:
882: /*
883: * Evaluate the argument using the set function. If invert
884: * is TRUE, we invert the sense of the function.
885: */
886: t = (!doEval || (* evalProc) (arglen, arg) ?
887: (invert ? False : True) :
888: (invert ? True : False));
889: free(arg);
890: break;
891: }
892: }
893: } else {
894: t = condPushBack;
895: condPushBack = None;
896: }
897: return (t);
898: }
899:
900: /*-
901: *-----------------------------------------------------------------------
902: * CondT --
903: * Parse a single term in the expression. This consists of a terminal
904: * symbol or Not and a terminal symbol (not including the binary
905: * operators):
906: * T -> defined(variable) | make(target) | exists(file) | symbol
907: * T -> ! T | ( E )
908: *
909: * Results:
910: * True, False or Err.
911: *
912: * Side Effects:
913: * Tokens are consumed.
914: *
915: *-----------------------------------------------------------------------
916: */
917: static Token
918: CondT(doEval)
919: Boolean doEval;
920: {
921: Token t;
922:
923: t = CondToken(doEval);
924:
925: if (t == EndOfFile) {
926: /*
927: * If we reached the end of the expression, the expression
928: * is malformed...
929: */
930: t = Err;
931: } else if (t == LParen) {
932: /*
933: * T -> ( E )
934: */
935: t = CondE(doEval);
936: if (t != Err) {
937: if (CondToken(doEval) != RParen) {
938: t = Err;
939: }
940: }
941: } else if (t == Not) {
942: t = CondT(doEval);
943: if (t == True) {
944: t = False;
945: } else if (t == False) {
946: t = True;
947: }
948: }
949: return (t);
950: }
951:
952: /*-
953: *-----------------------------------------------------------------------
954: * CondF --
955: * Parse a conjunctive factor (nice name, wot?)
956: * F -> T && F | T
957: *
958: * Results:
959: * True, False or Err
960: *
961: * Side Effects:
962: * Tokens are consumed.
963: *
964: *-----------------------------------------------------------------------
965: */
966: static Token
967: CondF(doEval)
968: Boolean doEval;
969: {
970: Token l, o;
971:
972: l = CondT(doEval);
973: if (l != Err) {
974: o = CondToken(doEval);
975:
976: if (o == And) {
977: /*
978: * F -> T && F
979: *
980: * If T is False, the whole thing will be False, but we have to
981: * parse the r.h.s. anyway (to throw it away).
982: * If T is True, the result is the r.h.s., be it an Err or no.
983: */
984: if (l == True) {
985: l = CondF(doEval);
986: } else {
987: (void) CondF(FALSE);
988: }
989: } else {
990: /*
991: * F -> T
992: */
993: CondPushBack (o);
994: }
995: }
996: return (l);
997: }
998:
999: /*-
1000: *-----------------------------------------------------------------------
1001: * CondE --
1002: * Main expression production.
1003: * E -> F || E | F
1004: *
1005: * Results:
1006: * True, False or Err.
1007: *
1008: * Side Effects:
1009: * Tokens are, of course, consumed.
1010: *
1011: *-----------------------------------------------------------------------
1012: */
1013: static Token
1014: CondE(doEval)
1015: Boolean doEval;
1016: {
1017: Token l, o;
1018:
1019: l = CondF(doEval);
1020: if (l != Err) {
1021: o = CondToken(doEval);
1022:
1023: if (o == Or) {
1024: /*
1025: * E -> F || E
1026: *
1027: * A similar thing occurs for ||, except that here we make sure
1028: * the l.h.s. is False before we bother to evaluate the r.h.s.
1029: * Once again, if l is False, the result is the r.h.s. and once
1030: * again if l is True, we parse the r.h.s. to throw it away.
1031: */
1032: if (l == False) {
1033: l = CondE(doEval);
1034: } else {
1035: (void) CondE(FALSE);
1036: }
1037: } else {
1038: /*
1039: * E -> F
1040: */
1041: CondPushBack (o);
1042: }
1043: }
1044: return (l);
1045: }
1046:
1047: /*-
1048: *-----------------------------------------------------------------------
1049: * Cond_Eval --
1050: * Evaluate the conditional in the passed line. The line
1051: * looks like this:
1052: * #<cond-type> <expr>
1053: * where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1054: * ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1055: * and <expr> consists of &&, ||, !, make(target), defined(variable)
1056: * and parenthetical groupings thereof.
1057: *
1058: * Results:
1059: * COND_PARSE if should parse lines after the conditional
1060: * COND_SKIP if should skip lines after the conditional
1061: * COND_INVALID if not a valid conditional.
1062: *
1063: * Side Effects:
1064: * None.
1065: *
1066: *-----------------------------------------------------------------------
1067: */
1068: int
1069: Cond_Eval (line)
1070: char *line; /* Line to parse */
1071: {
1072: struct If *ifp;
1073: Boolean isElse;
1074: Boolean value = FALSE;
1075: int level; /* Level at which to report errors. */
1076:
1077: level = PARSE_FATAL;
1078:
1079: for (line++; *line == ' ' || *line == '\t'; line++) {
1080: continue;
1081: }
1082:
1083: /*
1084: * Find what type of if we're dealing with. The result is left
1085: * in ifp and isElse is set TRUE if it's an elif line.
1086: */
1087: if (line[0] == 'e' && line[1] == 'l') {
1088: line += 2;
1089: isElse = TRUE;
1090: } else if (strncmp (line, "endif", 5) == 0) {
1091: /*
1092: * End of a conditional section. If skipIfLevel is non-zero, that
1093: * conditional was skipped, so lines following it should also be
1094: * skipped. Hence, we return COND_SKIP. Otherwise, the conditional
1095: * was read so succeeding lines should be parsed (think about it...)
1096: * so we return COND_PARSE, unless this endif isn't paired with
1097: * a decent if.
1098: */
1099: if (skipIfLevel != 0) {
1100: skipIfLevel -= 1;
1101: return (COND_SKIP);
1102: } else {
1103: if (condTop == MAXIF) {
1104: Parse_Error (level, "if-less endif");
1105: return (COND_INVALID);
1106: } else {
1107: skipLine = FALSE;
1108: condTop += 1;
1109: return (COND_PARSE);
1110: }
1111: }
1112: } else {
1113: isElse = FALSE;
1114: }
1.3 millert 1115:
1.1 deraadt 1116: /*
1117: * Figure out what sort of conditional it is -- what its default
1118: * function is, etc. -- by looking in the table of valid "ifs"
1119: */
1120: for (ifp = ifs; ifp->form != (char *)0; ifp++) {
1121: if (strncmp (ifp->form, line, ifp->formlen) == 0) {
1122: break;
1123: }
1124: }
1125:
1126: if (ifp->form == (char *) 0) {
1127: /*
1128: * Nothing fit. If the first word on the line is actually
1129: * "else", it's a valid conditional whose value is the inverse
1130: * of the previous if we parsed.
1131: */
1132: if (isElse && (line[0] == 's') && (line[1] == 'e')) {
1133: if (condTop == MAXIF) {
1134: Parse_Error (level, "if-less else");
1135: return (COND_INVALID);
1136: } else if (skipIfLevel == 0) {
1137: value = !condStack[condTop];
1138: } else {
1139: return (COND_SKIP);
1140: }
1141: } else {
1142: /*
1143: * Not a valid conditional type. No error...
1144: */
1145: return (COND_INVALID);
1146: }
1147: } else {
1148: if (isElse) {
1149: if (condTop == MAXIF) {
1150: Parse_Error (level, "if-less elif");
1151: return (COND_INVALID);
1152: } else if (skipIfLevel != 0) {
1153: /*
1154: * If skipping this conditional, just ignore the whole thing.
1155: * If we don't, the user might be employing a variable that's
1156: * undefined, for which there's an enclosing ifdef that
1157: * we're skipping...
1158: */
1159: return(COND_SKIP);
1160: }
1161: } else if (skipLine) {
1162: /*
1163: * Don't even try to evaluate a conditional that's not an else if
1164: * we're skipping things...
1165: */
1166: skipIfLevel += 1;
1167: return(COND_SKIP);
1168: }
1169:
1170: /*
1171: * Initialize file-global variables for parsing
1172: */
1173: condDefProc = ifp->defProc;
1174: condInvert = ifp->doNot;
1.3 millert 1175:
1.1 deraadt 1176: line += ifp->formlen;
1.3 millert 1177:
1.1 deraadt 1178: while (*line == ' ' || *line == '\t') {
1179: line++;
1180: }
1.3 millert 1181:
1.1 deraadt 1182: condExpr = line;
1183: condPushBack = None;
1.3 millert 1184:
1.1 deraadt 1185: switch (CondE(TRUE)) {
1186: case True:
1187: if (CondToken(TRUE) == EndOfFile) {
1188: value = TRUE;
1189: break;
1190: }
1191: goto err;
1192: /*FALLTHRU*/
1193: case False:
1194: if (CondToken(TRUE) == EndOfFile) {
1195: value = FALSE;
1196: break;
1197: }
1198: /*FALLTHRU*/
1199: case Err:
1200: err:
1201: Parse_Error (level, "Malformed conditional (%s)",
1202: line);
1203: return (COND_INVALID);
1204: default:
1205: break;
1206: }
1207: }
1208: if (!isElse) {
1209: condTop -= 1;
1210: } else if ((skipIfLevel != 0) || condStack[condTop]) {
1211: /*
1212: * If this is an else-type conditional, it should only take effect
1213: * if its corresponding if was evaluated and FALSE. If its if was
1214: * TRUE or skipped, we return COND_SKIP (and start skipping in case
1215: * we weren't already), leaving the stack unmolested so later elif's
1216: * don't screw up...
1217: */
1218: skipLine = TRUE;
1219: return (COND_SKIP);
1220: }
1221:
1222: if (condTop < 0) {
1223: /*
1224: * This is the one case where we can definitely proclaim a fatal
1225: * error. If we don't, we're hosed.
1226: */
1227: Parse_Error (PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
1228: return (COND_INVALID);
1229: } else {
1230: condStack[condTop] = value;
1231: skipLine = !value;
1232: return (value ? COND_PARSE : COND_SKIP);
1233: }
1234: }
1235:
1236: /*-
1237: *-----------------------------------------------------------------------
1238: * Cond_End --
1239: * Make sure everything's clean at the end of a makefile.
1240: *
1241: * Results:
1242: * None.
1243: *
1244: * Side Effects:
1245: * Parse_Error will be called if open conditionals are around.
1246: *
1247: *-----------------------------------------------------------------------
1248: */
1249: void
1250: Cond_End()
1251: {
1252: if (condTop != MAXIF) {
1253: Parse_Error(PARSE_FATAL, "%d open conditional%s", MAXIF-condTop,
1254: MAXIF-condTop == 1 ? "" : "s");
1255: }
1256: condTop = MAXIF;
1257: }