Merge from vendor branch HEIMDAL:
[dragonfly.git] / usr.bin / make / cond.c
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  * $FreeBSD: src/usr.bin/make/cond.c,v 1.12.2.1 2003/07/22 08:03:13 ru Exp $
41  * $DragonFly: src/usr.bin/make/cond.c,v 1.22 2005/01/09 23:14:42 okumoto Exp $
42  */
43
44 /*-
45  * cond.c --
46  *      Functions to handle conditionals in a makefile.
47  *
48  * Interface:
49  *      Cond_Eval       Evaluate the conditional in the passed line.
50  *
51  */
52
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <ctype.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  */
101 typedef enum {
102     And, Or, Not, True, False, LParen, RParen, EndOfFile, None, Err
103 } Token;
104
105 typedef 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  */
111 static void CondPushBack(Token);
112 static int CondGetArg(char **, char **, const char *, Boolean);
113 static CondProc CondDoDefined;
114 static CondProc CondDoMake;
115 static CondProc CondDoExists;
116 static CondProc CondDoTarget;
117 static char *CondCvtArg(char *, double *);
118 static Token CondToken(Boolean);
119 static Token CondT(Boolean);
120 static Token CondF(Boolean);
121 static Token CondE(Boolean);
122
123 static struct If {
124     const 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
137 static Boolean    condInvert;           /* Invert the default function */
138 static Boolean    (*condDefProc)        /* Default function to apply */
139 (int, char *);
140 static char       *condExpr;            /* The expression to parse */
141 static Token      condPushBack=None;    /* Single push-back token used in
142                                          * parsing */
143
144 #define MAXIF           30        /* greatest depth of #if'ing */
145
146 static Boolean    condStack[MAXIF];     /* Stack of conditionals's values */
147 static int        condLineno[MAXIF];    /* Line numbers of the opening .if */
148 static int        condTop = MAXIF;      /* Top-most conditional */
149 static int        skipIfLevel=0;        /* Depth of skipped conditionals */
150 static int        skipIfLineno[MAXIF];  /* Line numbers of skipped .ifs */
151 static 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  */
168 static void
169 CondPushBack(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  */
190 static int
191 CondGetArg(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;
238             Boolean     doFree;
239
240             cp2 = Var_Parse(cp, VAR_CMD, TRUE, &len, &doFree);
241
242             Buf_AddBytes(buf, strlen(cp2), (Byte *)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  */
288 static Boolean
289 CondDoDefined(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  * CondStrMatch --
309  *      Front-end for Str_Match so it returns 0 on match and non-zero
310  *      on mismatch. Callback function for CondDoMake via Lst_Find
311  *
312  * Results:
313  *      0 if string matches pattern
314  *
315  * Side Effects:
316  *      None
317  *
318  *-----------------------------------------------------------------------
319  */
320 static int
321 CondStrMatch(const void *string, const void *pattern)
322 {
323
324     return (!Str_Match(string, pattern));
325 }
326
327 /*-
328  *-----------------------------------------------------------------------
329  * CondDoMake --
330  *      Handle the 'make' function for conditionals.
331  *
332  * Results:
333  *      TRUE if the given target is being made.
334  *
335  * Side Effects:
336  *      None.
337  *
338  *-----------------------------------------------------------------------
339  */
340 static Boolean
341 CondDoMake(int argLen, char *arg)
342 {
343     char    savec = arg[argLen];
344     Boolean result;
345
346     arg[argLen] = '\0';
347     if (Lst_Find(&create, arg, CondStrMatch) == NULL) {
348         result = FALSE;
349     } else {
350         result = TRUE;
351     }
352     arg[argLen] = savec;
353     return (result);
354 }
355
356 /*-
357  *-----------------------------------------------------------------------
358  * CondDoExists --
359  *      See if the given file exists.
360  *
361  * Results:
362  *      TRUE if the file exists and FALSE if it does not.
363  *
364  * Side Effects:
365  *      None.
366  *
367  *-----------------------------------------------------------------------
368  */
369 static Boolean
370 CondDoExists(int argLen, char *arg)
371 {
372     char    savec = arg[argLen];
373     Boolean result;
374     char    *path;
375
376     arg[argLen] = '\0';
377     path = Dir_FindFile(arg, &dirSearchPath);
378     if (path != NULL) {
379         result = TRUE;
380         free(path);
381     } else {
382         result = FALSE;
383     }
384     arg[argLen] = savec;
385     return (result);
386 }
387
388 /*-
389  *-----------------------------------------------------------------------
390  * CondDoTarget --
391  *      See if the given node exists and is an actual target.
392  *
393  * Results:
394  *      TRUE if the node exists as a target and FALSE if it does not.
395  *
396  * Side Effects:
397  *      None.
398  *
399  *-----------------------------------------------------------------------
400  */
401 static Boolean
402 CondDoTarget(int argLen, char *arg)
403 {
404     char    savec = arg[argLen];
405     Boolean result;
406     GNode   *gn;
407
408     arg[argLen] = '\0';
409     gn = Targ_FindNode(arg, TARG_NOCREATE);
410     if ((gn != NULL) && !OP_NOP(gn->type)) {
411         result = TRUE;
412     } else {
413         result = FALSE;
414     }
415     arg[argLen] = savec;
416     return (result);
417 }
418
419 /*-
420  *-----------------------------------------------------------------------
421  * CondCvtArg --
422  *      Convert the given number into a double. If the number begins
423  *      with 0x, it is interpreted as a hexadecimal integer
424  *      and converted to a double from there. All other strings just have
425  *      strtod called on them.
426  *
427  * Results:
428  *      Sets 'value' to double value of string.
429  *      Returns address of the first character after the last valid
430  *      character of the converted number.
431  *
432  * Side Effects:
433  *      Can change 'value' even if string is not a valid number.
434  *
435  *
436  *-----------------------------------------------------------------------
437  */
438 static char *
439 CondCvtArg(char *str, double *value)
440 {
441     if ((*str == '0') && (str[1] == 'x')) {
442         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
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(Boolean doEval)
479 {
480     Token         t;
481
482     if (condPushBack == None) {
483         while (*condExpr == ' ' || *condExpr == '\t') {
484             condExpr++;
485         }
486         switch (*condExpr) {
487             case '(':
488                 t = LParen;
489                 condExpr++;
490                 break;
491             case ')':
492                 t = RParen;
493                 condExpr++;
494                 break;
495             case '|':
496                 if (condExpr[1] == '|') {
497                     condExpr++;
498                 }
499                 condExpr++;
500                 t = Or;
501                 break;
502             case '&':
503                 if (condExpr[1] == '&') {
504                     condExpr++;
505                 }
506                 condExpr++;
507                 t = And;
508                 break;
509             case '!':
510                 t = Not;
511                 condExpr++;
512                 break;
513             case '\n':
514             case '\0':
515                 t = EndOfFile;
516                 break;
517             case '$': {
518                 char    *lhs;
519                 char    *rhs;
520                 const char      *op;
521                 size_t  varSpecLen;
522                 Boolean doFree;
523
524                 /*
525                  * Parse the variable spec and skip over it, saving its
526                  * value in lhs.
527                  */
528                 t = Err;
529                 lhs = Var_Parse(condExpr, VAR_CMD, doEval,
530                     &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                             size_t 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, (size_t *)NULL);
656                     Buf_Destroy(buf, FALSE);
657
658                     DEBUGF(COND, ("lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
659                            lhs, string, op));
660                     /*
661                      * Null-terminate rhs and perform the comparison.
662                      * t is set to the result.
663                      */
664                     if (*op == '=') {
665                         t = strcmp(lhs, string) ? False : True;
666                     } else {
667                         t = strcmp(lhs, string) ? True : False;
668                     }
669                     free(string);
670                     if (rhs == condExpr) {
671                         if (!qt && *cp == ')')
672                             condExpr = cp;
673                         else
674                             condExpr = cp + 1;
675                     }
676                 } else {
677                     /*
678                      * rhs is either a float or an integer. Convert both the
679                      * lhs and the rhs to a double and compare the two.
680                      */
681                     double      left, right;
682                     char        *string;
683
684                     if (*CondCvtArg(lhs, &left) != '\0')
685                         goto do_string_compare;
686                     if (*rhs == '$') {
687                         size_t len;
688                         Boolean freeIt;
689
690                         string = Var_Parse(rhs, VAR_CMD, doEval, &len, &freeIt);
691                         if (string == var_Error) {
692                             right = 0.0;
693                         } else {
694                             if (*CondCvtArg(string, &right) != '\0') {
695                                 if (freeIt)
696                                     free(string);
697                                 goto do_string_compare;
698                             }
699                             if (freeIt)
700                                 free(string);
701                             if (rhs == condExpr)
702                                 condExpr += len;
703                         }
704                     } else {
705                         char *c = CondCvtArg(rhs, &right);
706                         if (c == rhs)
707                             goto do_string_compare;
708                         if (rhs == condExpr) {
709                             /*
710                              * Skip over the right-hand side
711                              */
712                             condExpr = c;
713                         }
714                     }
715
716                     DEBUGF(COND, ("left = %f, right = %f, op = %.2s\n", left,
717                            right, op));
718                     switch (op[0]) {
719                     case '!':
720                         if (op[1] != '=') {
721                             Parse_Error(PARSE_WARNING,
722                                         "Unknown operator");
723                             goto error;
724                         }
725                         t = (left != right ? True : False);
726                         break;
727                     case '=':
728                         if (op[1] != '=') {
729                             Parse_Error(PARSE_WARNING,
730                                         "Unknown operator");
731                             goto error;
732                         }
733                         t = (left == right ? True : False);
734                         break;
735                     case '<':
736                         if (op[1] == '=') {
737                             t = (left <= right ? True : False);
738                         } else {
739                             t = (left < right ? True : False);
740                         }
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                     default:
750                         break;
751                     }
752                 }
753 error:
754                 if (doFree)
755                     free(lhs);
756                 break;
757             }
758             default: {
759                 CondProc        *evalProc;
760                 Boolean         invert = FALSE;
761                 char            *arg;
762                 int             arglen;
763
764                 if (strncmp(condExpr, "defined", 7) == 0) {
765                     /*
766                      * Use CondDoDefined to evaluate the argument and
767                      * CondGetArg to extract the argument from the 'function
768                      * call'.
769                      */
770                     evalProc = CondDoDefined;
771                     condExpr += 7;
772                     arglen = CondGetArg(&condExpr, &arg, "defined", TRUE);
773                     if (arglen == 0) {
774                         condExpr -= 7;
775                         goto use_default;
776                     }
777                 } else if (strncmp(condExpr, "make", 4) == 0) {
778                     /*
779                      * Use CondDoMake to evaluate the argument and
780                      * CondGetArg to extract the argument from the 'function
781                      * call'.
782                      */
783                     evalProc = CondDoMake;
784                     condExpr += 4;
785                     arglen = CondGetArg(&condExpr, &arg, "make", TRUE);
786                     if (arglen == 0) {
787                         condExpr -= 4;
788                         goto use_default;
789                     }
790                 } else if (strncmp(condExpr, "exists", 6) == 0) {
791                     /*
792                      * Use CondDoExists to evaluate the argument and
793                      * CondGetArg to extract the argument from the
794                      * 'function call'.
795                      */
796                     evalProc = CondDoExists;
797                     condExpr += 6;
798                     arglen = CondGetArg(&condExpr, &arg, "exists", TRUE);
799                     if (arglen == 0) {
800                         condExpr -= 6;
801                         goto use_default;
802                     }
803                 } else if (strncmp(condExpr, "empty", 5) == 0) {
804                     /*
805                      * Use Var_Parse to parse the spec in parens and return
806                      * True if the resulting string is empty.
807                      */
808                     size_t length;
809                     Boolean doFree;
810                     char    *val;
811
812                     condExpr += 5;
813
814                     for (arglen = 0;
815                          condExpr[arglen] != '(' && condExpr[arglen] != '\0';
816                          arglen += 1)
817                         continue;
818
819                     if (condExpr[arglen] != '\0') {
820                         val = Var_Parse(&condExpr[arglen - 1], VAR_CMD,
821                                         FALSE, &length, &doFree);
822                         if (val == var_Error) {
823                             t = Err;
824                         } else {
825                             /*
826                              * A variable is empty when it just contains
827                              * spaces... 4/15/92, christos
828                              */
829                             char *p;
830                             for (p = val; *p && isspace((unsigned char)*p); p++)
831                                 continue;
832                             t = (*p == '\0') ? True : False;
833                         }
834                         if (doFree) {
835                             free(val);
836                         }
837                         /*
838                          * Advance condExpr to beyond the closing ). Note that
839                          * we subtract one from arglen + length b/c length
840                          * is calculated from condExpr[arglen - 1].
841                          */
842                         condExpr += arglen + length - 1;
843                     } else {
844                         condExpr -= 5;
845                         goto use_default;
846                     }
847                     break;
848                 } else if (strncmp(condExpr, "target", 6) == 0) {
849                     /*
850                      * Use CondDoTarget to evaluate the argument and
851                      * CondGetArg to extract the argument from the
852                      * 'function call'.
853                      */
854                     evalProc = CondDoTarget;
855                     condExpr += 6;
856                     arglen = CondGetArg(&condExpr, &arg, "target", TRUE);
857                     if (arglen == 0) {
858                         condExpr -= 6;
859                         goto use_default;
860                     }
861                 } else {
862                     /*
863                      * The symbol is itself the argument to the default
864                      * function. We advance condExpr to the end of the symbol
865                      * by hand (the next whitespace, closing paren or
866                      * binary operator) and set to invert the evaluation
867                      * function if condInvert is TRUE.
868                      */
869                 use_default:
870                     invert = condInvert;
871                     evalProc = condDefProc;
872                     arglen = CondGetArg(&condExpr, &arg, "", FALSE);
873                 }
874
875                 /*
876                  * Evaluate the argument using the set function. If invert
877                  * is TRUE, we invert the sense of the function.
878                  */
879                 t = (!doEval || (* evalProc) (arglen, arg) ?
880                      (invert ? False : True) :
881                      (invert ? True : False));
882                 free(arg);
883                 break;
884             }
885         }
886     } else {
887         t = condPushBack;
888         condPushBack = None;
889     }
890     return (t);
891 }
892
893 /*-
894  *-----------------------------------------------------------------------
895  * CondT --
896  *      Parse a single term in the expression. This consists of a terminal
897  *      symbol or Not and a terminal symbol (not including the binary
898  *      operators):
899  *          T -> defined(variable) | make(target) | exists(file) | symbol
900  *          T -> ! T | ( E )
901  *
902  * Results:
903  *      True, False or Err.
904  *
905  * Side Effects:
906  *      Tokens are consumed.
907  *
908  *-----------------------------------------------------------------------
909  */
910 static Token
911 CondT(Boolean doEval)
912 {
913     Token   t;
914
915     t = CondToken(doEval);
916
917     if (t == EndOfFile) {
918         /*
919          * If we reached the end of the expression, the expression
920          * is malformed...
921          */
922         t = Err;
923     } else if (t == LParen) {
924         /*
925          * T -> ( E )
926          */
927         t = CondE(doEval);
928         if (t != Err) {
929             if (CondToken(doEval) != RParen) {
930                 t = Err;
931             }
932         }
933     } else if (t == Not) {
934         t = CondT(doEval);
935         if (t == True) {
936             t = False;
937         } else if (t == False) {
938             t = True;
939         }
940     }
941     return (t);
942 }
943
944 /*-
945  *-----------------------------------------------------------------------
946  * CondF --
947  *      Parse a conjunctive factor (nice name, wot?)
948  *          F -> T && F | T
949  *
950  * Results:
951  *      True, False or Err
952  *
953  * Side Effects:
954  *      Tokens are consumed.
955  *
956  *-----------------------------------------------------------------------
957  */
958 static Token
959 CondF(Boolean doEval)
960 {
961     Token   l, o;
962
963     l = CondT(doEval);
964     if (l != Err) {
965         o = CondToken(doEval);
966
967         if (o == And) {
968             /*
969              * F -> T && F
970              *
971              * If T is False, the whole thing will be False, but we have to
972              * parse the r.h.s. anyway (to throw it away).
973              * If T is True, the result is the r.h.s., be it an Err or no.
974              */
975             if (l == True) {
976                 l = CondF(doEval);
977             } else {
978                  CondF(FALSE);
979             }
980         } else {
981             /*
982              * F -> T
983              */
984             CondPushBack(o);
985         }
986     }
987     return (l);
988 }
989
990 /*-
991  *-----------------------------------------------------------------------
992  * CondE --
993  *      Main expression production.
994  *          E -> F || E | F
995  *
996  * Results:
997  *      True, False or Err.
998  *
999  * Side Effects:
1000  *      Tokens are, of course, consumed.
1001  *
1002  *-----------------------------------------------------------------------
1003  */
1004 static Token
1005 CondE(Boolean doEval)
1006 {
1007     Token   l, o;
1008
1009     l = CondF(doEval);
1010     if (l != Err) {
1011         o = CondToken(doEval);
1012
1013         if (o == Or) {
1014             /*
1015              * E -> F || E
1016              *
1017              * A similar thing occurs for ||, except that here we make sure
1018              * the l.h.s. is False before we bother to evaluate the r.h.s.
1019              * Once again, if l is False, the result is the r.h.s. and once
1020              * again if l is True, we parse the r.h.s. to throw it away.
1021              */
1022             if (l == False) {
1023                 l = CondE(doEval);
1024             } else {
1025                  CondE(FALSE);
1026             }
1027         } else {
1028             /*
1029              * E -> F
1030              */
1031             CondPushBack(o);
1032         }
1033     }
1034     return (l);
1035 }
1036
1037 /*-
1038  *-----------------------------------------------------------------------
1039  * Cond_Eval --
1040  *      Evaluate the conditional in the passed line. The line
1041  *      looks like this:
1042  *          #<cond-type> <expr>
1043  *      where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1044  *      ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1045  *      and <expr> consists of &&, ||, !, make(target), defined(variable)
1046  *      and parenthetical groupings thereof.
1047  *
1048  * Results:
1049  *      COND_PARSE      if should parse lines after the conditional
1050  *      COND_SKIP       if should skip lines after the conditional
1051  *      COND_INVALID    if not a valid conditional.
1052  *
1053  * Side Effects:
1054  *      None.
1055  *
1056  *-----------------------------------------------------------------------
1057  */
1058 int
1059 Cond_Eval(char *line)
1060 {
1061     struct If       *ifp;
1062     Boolean         isElse;
1063     Boolean         value = FALSE;
1064     int             level;      /* Level at which to report errors. */
1065     int             lineno;
1066
1067     level = PARSE_FATAL;
1068     lineno = curFile.lineno;
1069
1070     for (line++; *line == ' ' || *line == '\t'; line++) {
1071         continue;
1072     }
1073
1074     /*
1075      * Find what type of if we're dealing with. The result is left
1076      * in ifp and isElse is set TRUE if it's an elif line.
1077      */
1078     if (line[0] == 'e' && line[1] == 'l') {
1079         line += 2;
1080         isElse = TRUE;
1081     } else if (strncmp(line, "endif", 5) == 0) {
1082         /*
1083          * End of a conditional section. If skipIfLevel is non-zero, that
1084          * conditional was skipped, so lines following it should also be
1085          * skipped. Hence, we return COND_SKIP. Otherwise, the conditional
1086          * was read so succeeding lines should be parsed (think about it...)
1087          * so we return COND_PARSE, unless this endif isn't paired with
1088          * a decent if.
1089          */
1090         if (skipIfLevel != 0) {
1091             skipIfLevel -= 1;
1092             return (COND_SKIP);
1093         } else {
1094             if (condTop == MAXIF) {
1095                 Parse_Error(level, "if-less endif");
1096                 return (COND_INVALID);
1097             } else {
1098                 skipLine = FALSE;
1099                 condTop += 1;
1100                 return (COND_PARSE);
1101             }
1102         }
1103     } else {
1104         isElse = FALSE;
1105     }
1106
1107     /*
1108      * Figure out what sort of conditional it is -- what its default
1109      * function is, etc. -- by looking in the table of valid "ifs"
1110      */
1111     for (ifp = ifs; ifp->form != NULL; ifp++) {
1112         if (strncmp(ifp->form, line, ifp->formlen) == 0) {
1113             break;
1114         }
1115     }
1116
1117     if (ifp->form == NULL) {
1118         /*
1119          * Nothing fit. If the first word on the line is actually
1120          * "else", it's a valid conditional whose value is the inverse
1121          * of the previous if we parsed.
1122          */
1123         if (isElse && (line[0] == 's') && (line[1] == 'e')) {
1124             if (condTop == MAXIF) {
1125                 Parse_Error(level, "if-less else");
1126                 return (COND_INVALID);
1127             } else if (skipIfLevel == 0) {
1128                 value = !condStack[condTop];
1129                 lineno = condLineno[condTop];
1130             } else {
1131                 return (COND_SKIP);
1132             }
1133         } else {
1134             /*
1135              * Not a valid conditional type. No error...
1136              */
1137             return (COND_INVALID);
1138         }
1139     } else {
1140         if (isElse) {
1141             if (condTop == MAXIF) {
1142                 Parse_Error(level, "if-less elif");
1143                 return (COND_INVALID);
1144             } else if (skipIfLevel != 0) {
1145                 /*
1146                  * If skipping this conditional, just ignore the whole thing.
1147                  * If we don't, the user might be employing a variable that's
1148                  * undefined, for which there's an enclosing ifdef that
1149                  * we're skipping...
1150                  */
1151                 skipIfLineno[skipIfLevel - 1] = lineno;
1152                 return (COND_SKIP);
1153             }
1154         } else if (skipLine) {
1155             /*
1156              * Don't even try to evaluate a conditional that's not an else if
1157              * we're skipping things...
1158              */
1159             skipIfLineno[skipIfLevel] = lineno;
1160             skipIfLevel += 1;
1161             return (COND_SKIP);
1162         }
1163
1164         /*
1165          * Initialize file-global variables for parsing
1166          */
1167         condDefProc = ifp->defProc;
1168         condInvert = ifp->doNot;
1169
1170         line += ifp->formlen;
1171
1172         while (*line == ' ' || *line == '\t') {
1173             line++;
1174         }
1175
1176         condExpr = line;
1177         condPushBack = None;
1178
1179         switch (CondE(TRUE)) {
1180             case True:
1181                 if (CondToken(TRUE) == EndOfFile) {
1182                     value = TRUE;
1183                     break;
1184                 }
1185                 goto err;
1186                 /*FALLTHRU*/
1187             case False:
1188                 if (CondToken(TRUE) == EndOfFile) {
1189                     value = FALSE;
1190                     break;
1191                 }
1192                 /*FALLTHRU*/
1193             case Err:
1194             err:
1195                 Parse_Error(level, "Malformed conditional (%s)",
1196                              line);
1197                 return (COND_INVALID);
1198             default:
1199                 break;
1200         }
1201     }
1202     if (!isElse) {
1203         condTop -= 1;
1204     } else if ((skipIfLevel != 0) || condStack[condTop]) {
1205         /*
1206          * If this is an else-type conditional, it should only take effect
1207          * if its corresponding if was evaluated and FALSE. If its if was
1208          * TRUE or skipped, we return COND_SKIP (and start skipping in case
1209          * we weren't already), leaving the stack unmolested so later elif's
1210          * don't screw up...
1211          */
1212         skipLine = TRUE;
1213         return (COND_SKIP);
1214     }
1215
1216     if (condTop < 0) {
1217         /*
1218          * This is the one case where we can definitely proclaim a fatal
1219          * error. If we don't, we're hosed.
1220          */
1221         Parse_Error(PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
1222         return (COND_INVALID);
1223     } else {
1224         condStack[condTop] = value;
1225         condLineno[condTop] = lineno;
1226         skipLine = !value;
1227         return (value ? COND_PARSE : COND_SKIP);
1228     }
1229 }
1230
1231 /*-
1232  *-----------------------------------------------------------------------
1233  * Cond_End --
1234  *      Make sure everything's clean at the end of a makefile.
1235  *
1236  * Results:
1237  *      None.
1238  *
1239  * Side Effects:
1240  *      Parse_Error will be called if open conditionals are around.
1241  *
1242  *-----------------------------------------------------------------------
1243  */
1244 void
1245 Cond_End(void)
1246 {
1247     int level;
1248
1249     if (condTop != MAXIF) {
1250         Parse_Error(PARSE_FATAL, "%d open conditional%s:",
1251             MAXIF - condTop + skipIfLevel,
1252             MAXIF - condTop + skipIfLevel== 1 ? "" : "s");
1253
1254         for (level = skipIfLevel; level > 0; level--)
1255                 Parse_Error(PARSE_FATAL, "\t%*sat line %d (skipped)",
1256                     MAXIF - condTop + level + 1, "", skipIfLineno[level - 1]);
1257         for (level = condTop; level < MAXIF; level++)
1258                 Parse_Error(PARSE_FATAL, "\t%*sat line %d "
1259                     "(evaluated to %s)", MAXIF - level + skipIfLevel, "",
1260                     condLineno[level], condStack[level] ? "true" : "false");
1261     }
1262     condTop = MAXIF;
1263 }