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