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