Annotation of src/usr.bin/make/cond.c, Revision 1.8
1.8 ! espie 1: /* $OpenBSD: cond.c,v 1.7 1999/12/09 18:18:24 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.8 ! espie 46: static char rcsid[] = "$OpenBSD: cond.c,v 1.7 1999/12/09 18:18:24 espie Exp $";
1.1 deraadt 47: #endif
48: #endif /* not lint */
49:
50: /*-
51: * cond.c --
52: * Functions to handle conditionals in a makefile.
53: *
54: * Interface:
55: * Cond_Eval Evaluate the conditional in the passed line.
56: *
57: */
58:
59: #include <ctype.h>
60: #include <math.h>
61: #include "make.h"
62: #include "hash.h"
63: #include "dir.h"
64: #include "buf.h"
65:
66: /*
67: * The parsing of conditional expressions is based on this grammar:
68: * E -> F || E
69: * E -> F
70: * F -> T && F
71: * F -> T
72: * T -> defined(variable)
73: * T -> make(target)
74: * T -> exists(file)
75: * T -> empty(varspec)
76: * T -> target(name)
77: * T -> symbol
78: * T -> $(varspec) op value
79: * T -> $(varspec) == "string"
80: * T -> $(varspec) != "string"
81: * T -> ( E )
82: * T -> ! T
83: * op -> == | != | > | < | >= | <=
84: *
85: * 'symbol' is some other symbol to which the default function (condDefProc)
86: * is applied.
87: *
88: * Tokens are scanned from the 'condExpr' string. The scanner (CondToken)
89: * will return And for '&' and '&&', Or for '|' and '||', Not for '!',
90: * LParen for '(', RParen for ')' and will evaluate the other terminal
91: * symbols, using either the default function or the function given in the
92: * terminal, and return the result as either True or False.
93: *
94: * All Non-Terminal functions (CondE, CondF and CondT) return Err on error.
95: */
96: typedef enum {
97: And, Or, Not, True, False, LParen, RParen, EndOfFile, None, Err
98: } Token;
99:
100: /*-
101: * Structures to handle elegantly the different forms of #if's. The
102: * last two fields are stored in condInvert and condDefProc, respectively.
103: */
1.3 millert 104: static void CondPushBack __P((Token));
1.5 espie 105: static size_t CondGetArg __P((char **, char **, char *, Boolean));
106: static Boolean CondDoDefined __P((size_t, char *));
1.1 deraadt 107: static int CondStrMatch __P((ClientData, ClientData));
1.5 espie 108: static Boolean CondDoMake __P((size_t, char *));
109: static Boolean CondDoExists __P((size_t, char *));
110: static Boolean CondDoTarget __P((size_t, char *));
1.1 deraadt 111: static Boolean CondCvtArg __P((char *, double *));
112: static Token CondToken __P((Boolean));
113: static Token CondT __P((Boolean));
114: static Token CondF __P((Boolean));
115: static Token CondE __P((Boolean));
116:
117: static struct If {
118: char *form; /* Form of if */
119: int formlen; /* Length of form */
120: Boolean doNot; /* TRUE if default function should be negated */
1.5 espie 121: Boolean (*defProc) __P((size_t, char *)); /* Default function to apply */
1.1 deraadt 122: } ifs[] = {
123: { "ifdef", 5, FALSE, CondDoDefined },
124: { "ifndef", 6, TRUE, CondDoDefined },
125: { "ifmake", 6, FALSE, CondDoMake },
126: { "ifnmake", 7, TRUE, CondDoMake },
127: { "if", 2, FALSE, CondDoDefined },
1.3 millert 128: { NULL, 0, FALSE, NULL }
1.1 deraadt 129: };
130:
131: static Boolean condInvert; /* Invert the default function */
1.3 millert 132: static Boolean (*condDefProc) /* Default function to apply */
1.5 espie 133: __P((size_t, char *));
1.1 deraadt 134: static char *condExpr; /* The expression to parse */
135: static Token condPushBack=None; /* Single push-back token used in
136: * parsing */
137:
138: #define MAXIF 30 /* greatest depth of #if'ing */
139:
140: static Boolean condStack[MAXIF]; /* Stack of conditionals's values */
141: static int condTop = MAXIF; /* Top-most conditional */
142: static int skipIfLevel=0; /* Depth of skipped conditionals */
143: static Boolean skipLine = FALSE; /* Whether the parse module is skipping
144: * lines */
145:
146: /*-
147: *-----------------------------------------------------------------------
148: * CondPushBack --
149: * Push back the most recent token read. We only need one level of
150: * this, so the thing is just stored in 'condPushback'.
151: *
152: * Results:
153: * None.
154: *
155: * Side Effects:
156: * condPushback is overwritten.
157: *
158: *-----------------------------------------------------------------------
159: */
160: static void
161: CondPushBack (t)
162: Token t; /* Token to push back into the "stream" */
163: {
164: condPushBack = t;
165: }
166:
167: /*-
168: *-----------------------------------------------------------------------
169: * CondGetArg --
170: * Find the argument of a built-in function.
171: *
172: * Results:
173: * The length of the argument and the address of the argument.
174: *
175: * Side Effects:
176: * The pointer is set to point to the closing parenthesis of the
177: * function call.
178: *
179: *-----------------------------------------------------------------------
180: */
1.5 espie 181: static size_t
182: CondGetArg(linePtr, argPtr, func, parens)
1.1 deraadt 183: char **linePtr;
184: char **argPtr;
185: char *func;
186: Boolean parens; /* TRUE if arg should be bounded by parens */
187: {
188: register char *cp;
1.5 espie 189: size_t argLen;
1.1 deraadt 190: register Buffer buf;
191:
192: cp = *linePtr;
193: if (parens) {
194: while (*cp != '(' && *cp != '\0') {
195: cp++;
196: }
197: if (*cp == '(') {
198: cp++;
199: }
200: }
201:
202: if (*cp == '\0') {
203: /*
204: * No arguments whatsoever. Because 'make' and 'defined' aren't really
205: * "reserved words", we don't print a message. I think this is better
206: * than hitting the user with a warning message every time s/he uses
207: * the word 'make' or 'defined' at the beginning of a symbol...
208: */
209: *argPtr = cp;
210: return (0);
211: }
212:
213: while (*cp == ' ' || *cp == '\t') {
214: cp++;
215: }
216:
217: /*
218: * Create a buffer for the argument and start it out at 16 characters
219: * long. Why 16? Why not?
220: */
221: buf = Buf_Init(16);
1.3 millert 222:
1.1 deraadt 223: while ((strchr(" \t)&|", *cp) == (char *)NULL) && (*cp != '\0')) {
224: if (*cp == '$') {
225: /*
226: * Parse the variable spec and install it as part of the argument
227: * if it's valid. We tell Var_Parse to complain on an undefined
228: * variable, so we don't do it too. Nor do we return an error,
229: * though perhaps we should...
230: */
231: char *cp2;
232: int len;
233: Boolean doFree;
234:
235: cp2 = Var_Parse(cp, VAR_CMD, TRUE, &len, &doFree);
236:
1.7 espie 237: Buf_AddString(buf, cp2);
1.1 deraadt 238: if (doFree) {
239: free(cp2);
240: }
241: cp += len;
242: } else {
1.5 espie 243: Buf_AddChar(buf, *cp);
1.1 deraadt 244: cp++;
245: }
246: }
247:
1.5 espie 248: Buf_AddChar(buf, '\0');
1.8 ! espie 249: *argPtr = Buf_Retrieve(buf);
! 250: argLen = Buf_Size(buf);
1.1 deraadt 251: Buf_Destroy(buf, FALSE);
252:
253: while (*cp == ' ' || *cp == '\t') {
254: cp++;
255: }
256: if (parens && *cp != ')') {
257: Parse_Error (PARSE_WARNING, "Missing closing parenthesis for %s()",
258: func);
259: return (0);
260: } else if (parens) {
261: /*
262: * Advance pointer past close parenthesis.
263: */
264: cp++;
265: }
1.3 millert 266:
1.1 deraadt 267: *linePtr = cp;
268: return (argLen);
269: }
270:
271: /*-
272: *-----------------------------------------------------------------------
273: * CondDoDefined --
274: * Handle the 'defined' function for conditionals.
275: *
276: * Results:
277: * TRUE if the given variable is defined.
278: *
279: * Side Effects:
280: * None.
281: *
282: *-----------------------------------------------------------------------
283: */
284: static Boolean
1.5 espie 285: CondDoDefined(argLen, arg)
286: size_t argLen;
1.1 deraadt 287: char *arg;
288: {
289: char savec = arg[argLen];
290: Boolean result;
291:
292: arg[argLen] = '\0';
1.6 espie 293: if (Var_Value(arg, VAR_CMD) != NULL)
1.1 deraadt 294: result = TRUE;
1.6 espie 295: else
1.1 deraadt 296: result = FALSE;
297: arg[argLen] = savec;
298: return (result);
299: }
300:
301: /*-
302: *-----------------------------------------------------------------------
303: * CondStrMatch --
304: * Front-end for Str_Match so it returns 0 on match and non-zero
305: * on mismatch. Callback function for CondDoMake via Lst_Find
306: *
307: * Results:
308: * 0 if string matches pattern
309: *
310: * Side Effects:
311: * None
312: *
313: *-----------------------------------------------------------------------
314: */
315: static int
316: CondStrMatch(string, pattern)
317: ClientData string;
318: ClientData pattern;
319: {
320: return(!Str_Match((char *) string,(char *) pattern));
321: }
322:
323: /*-
324: *-----------------------------------------------------------------------
325: * CondDoMake --
326: * Handle the 'make' function for conditionals.
327: *
328: * Results:
329: * TRUE if the given target is being made.
330: *
331: * Side Effects:
332: * None.
333: *
334: *-----------------------------------------------------------------------
335: */
336: static Boolean
337: CondDoMake (argLen, arg)
1.5 espie 338: size_t argLen;
1.1 deraadt 339: char *arg;
340: {
341: char savec = arg[argLen];
342: Boolean result;
343:
344: arg[argLen] = '\0';
345: if (Lst_Find (create, (ClientData)arg, CondStrMatch) == NILLNODE) {
346: result = FALSE;
347: } else {
348: result = TRUE;
349: }
350: arg[argLen] = savec;
351: return (result);
352: }
353:
354: /*-
355: *-----------------------------------------------------------------------
356: * CondDoExists --
357: * See if the given file exists.
358: *
359: * Results:
360: * TRUE if the file exists and FALSE if it does not.
361: *
362: * Side Effects:
363: * None.
364: *
365: *-----------------------------------------------------------------------
366: */
367: static Boolean
368: CondDoExists (argLen, arg)
1.5 espie 369: size_t argLen;
1.1 deraadt 370: char *arg;
371: {
372: char savec = arg[argLen];
373: Boolean result;
374: char *path;
375:
376: arg[argLen] = '\0';
377: path = Dir_FindFile(arg, dirSearchPath);
378: if (path != (char *)NULL) {
379: result = TRUE;
380: free(path);
381: } else {
382: result = FALSE;
383: }
384: arg[argLen] = savec;
385: return (result);
386: }
387:
388: /*-
389: *-----------------------------------------------------------------------
390: * CondDoTarget --
391: * See if the given node exists and is an actual target.
392: *
393: * Results:
394: * TRUE if the node exists as a target and FALSE if it does not.
395: *
396: * Side Effects:
397: * None.
398: *
399: *-----------------------------------------------------------------------
400: */
401: static Boolean
1.5 espie 402: CondDoTarget(argLen, arg)
403: size_t argLen;
1.1 deraadt 404: char *arg;
405: {
406: char savec = arg[argLen];
407: Boolean result;
408: GNode *gn;
409:
410: arg[argLen] = '\0';
411: gn = Targ_FindNode(arg, TARG_NOCREATE);
412: if ((gn != NILGNODE) && !OP_NOP(gn->type)) {
413: result = TRUE;
414: } else {
415: result = FALSE;
416: }
417: arg[argLen] = savec;
418: return (result);
419: }
420:
421:
422: /*-
423: *-----------------------------------------------------------------------
424: * CondCvtArg --
425: * Convert the given number into a double. If the number begins
426: * with 0x, it is interpreted as a hexadecimal integer
427: * and converted to a double from there. All other strings just have
428: * strtod called on them.
429: *
430: * Results:
431: * Sets 'value' to double value of string.
432: * Returns true if the string was a valid number, false o.w.
433: *
434: * Side Effects:
435: * Can change 'value' even if string is not a valid number.
1.3 millert 436: *
1.1 deraadt 437: *
438: *-----------------------------------------------------------------------
439: */
440: static Boolean
441: CondCvtArg(str, value)
442: register char *str;
443: double *value;
444: {
445: if ((*str == '0') && (str[1] == 'x')) {
446: register long i;
447:
448: for (str += 2, i = 0; *str; str++) {
449: int x;
450: if (isdigit((unsigned char) *str))
451: x = *str - '0';
452: else if (isxdigit((unsigned char) *str))
453: x = 10 + *str - isupper((unsigned char) *str) ? 'A' : 'a';
454: else
455: return FALSE;
456: i = (i << 4) + x;
457: }
458: *value = (double) i;
459: return TRUE;
460: }
461: else {
462: char *eptr;
463: *value = strtod(str, &eptr);
464: return *eptr == '\0';
465: }
466: }
467:
468: /*-
469: *-----------------------------------------------------------------------
470: * CondToken --
471: * Return the next token from the input.
472: *
473: * Results:
474: * A Token for the next lexical token in the stream.
475: *
476: * Side Effects:
477: * condPushback will be set back to None if it is used.
478: *
479: *-----------------------------------------------------------------------
480: */
481: static Token
482: CondToken(doEval)
483: Boolean doEval;
484: {
485: Token t;
486:
487: if (condPushBack == None) {
488: while (*condExpr == ' ' || *condExpr == '\t') {
489: condExpr++;
490: }
491: switch (*condExpr) {
492: case '(':
493: t = LParen;
494: condExpr++;
495: break;
496: case ')':
497: t = RParen;
498: condExpr++;
499: break;
500: case '|':
501: if (condExpr[1] == '|') {
502: condExpr++;
503: }
504: condExpr++;
505: t = Or;
506: break;
507: case '&':
508: if (condExpr[1] == '&') {
509: condExpr++;
510: }
511: condExpr++;
512: t = And;
513: break;
514: case '!':
515: t = Not;
516: condExpr++;
517: break;
518: case '\n':
519: case '\0':
520: t = EndOfFile;
521: break;
522: case '$': {
523: char *lhs;
524: char *rhs;
525: char *op;
526: int varSpecLen;
527: Boolean doFree;
528:
529: /*
530: * Parse the variable spec and skip over it, saving its
531: * value in lhs.
532: */
533: t = Err;
534: lhs = Var_Parse(condExpr, VAR_CMD, doEval,&varSpecLen,&doFree);
535: if (lhs == var_Error) {
536: /*
537: * Even if !doEval, we still report syntax errors, which
538: * is what getting var_Error back with !doEval means.
539: */
540: return(Err);
541: }
542: condExpr += varSpecLen;
543:
544: if (!isspace((unsigned char) *condExpr) &&
545: strchr("!=><", *condExpr) == NULL) {
546: Buffer buf;
547:
548: buf = Buf_Init(0);
549:
1.7 espie 550: Buf_AddString(buf, lhs);
1.1 deraadt 551:
552: if (doFree)
553: free(lhs);
554:
555: for (;*condExpr && !isspace((unsigned char) *condExpr);
556: condExpr++)
1.5 espie 557: Buf_AddChar(buf, *condExpr);
1.1 deraadt 558:
1.5 espie 559: Buf_AddChar(buf, '\0');
1.8 ! espie 560: lhs = Buf_Retrieve(buf);
! 561: varSpecLen = Buf_Size(buf);
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.7 espie 643: Buf_AddString(buf, 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.8 ! espie 658: string = Buf_Retrieve(buf);
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: }