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