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