- New function Buf_AppendRange(), which is given a pointer to a string and
[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.26 2005/01/27 02:28:48 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_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  */
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
544                     buf = Buf_Init(0);
545
546                     Buf_Append(buf, lhs);
547
548                     if (doFree)
549                         free(lhs);
550
551                     for (;*condExpr && !isspace((unsigned char) *condExpr);
552                          condExpr++)
553                         Buf_AddByte(buf, (Byte)*condExpr);
554
555                     Buf_AddByte(buf, (Byte)'\0');
556                     lhs = (char *)Buf_GetAll(buf, &varSpecLen);
557                     Buf_Destroy(buf, FALSE);
558
559                     doFree = TRUE;
560                 }
561
562                 /*
563                  * Skip whitespace to get to the operator
564                  */
565                 while (isspace((unsigned char)*condExpr))
566                     condExpr++;
567
568                 /*
569                  * Make sure the operator is a valid one. If it isn't a
570                  * known relational operator, pretend we got a
571                  * != 0 comparison.
572                  */
573                 op = condExpr;
574                 switch (*condExpr) {
575                     case '!':
576                     case '=':
577                     case '<':
578                     case '>':
579                         if (condExpr[1] == '=') {
580                             condExpr += 2;
581                         } else {
582                             condExpr += 1;
583                         }
584                         break;
585                     default:
586                         op = "!=";
587                         rhs = "0";
588
589                         goto do_compare;
590                 }
591                 while (isspace((unsigned char)*condExpr)) {
592                     condExpr++;
593                 }
594                 if (*condExpr == '\0') {
595                     Parse_Error(PARSE_WARNING,
596                                 "Missing right-hand-side of operator");
597                     goto error;
598                 }
599                 rhs = condExpr;
600 do_compare:
601                 if (*rhs == '"') {
602                     /*
603                      * Doing a string comparison. Only allow == and != for
604                      * operators.
605                      */
606                     char    *string;
607                     char    *cp, *cp2;
608                     int     qt;
609                     Buffer  *buf;
610
611 do_string_compare:
612                     if (((*op != '!') && (*op != '=')) || (op[1] != '=')) {
613                         Parse_Error(PARSE_WARNING,
614                 "String comparison operator should be either == or !=");
615                         goto error;
616                     }
617
618                     buf = Buf_Init(0);
619                     qt = *rhs == '"' ? 1 : 0;
620
621                     for (cp = &rhs[qt];
622                          ((qt && (*cp != '"')) ||
623                           (!qt && strchr(" \t)", *cp) == NULL)) &&
624                          (*cp != '\0'); cp++) {
625                         if ((*cp == '\\') && (cp[1] != '\0')) {
626                             /*
627                              * Backslash escapes things -- skip over next
628                              * character, if it exists.
629                              */
630                             cp++;
631                             Buf_AddByte(buf, (Byte)*cp);
632                         } else if (*cp == '$') {
633                             size_t len;
634                             Boolean freeIt;
635
636                             cp2 = Var_Parse(cp, VAR_CMD, doEval, &len, &freeIt);
637                             if (cp2 != var_Error) {
638                                 Buf_Append(buf, cp2);
639                                 if (freeIt) {
640                                     free(cp2);
641                                 }
642                                 cp += len - 1;
643                             } else {
644                                 Buf_AddByte(buf, (Byte)*cp);
645                             }
646                         } else {
647                             Buf_AddByte(buf, (Byte)*cp);
648                         }
649                     }
650
651                     Buf_AddByte(buf, (Byte)0);
652
653                     string = (char *)Buf_GetAll(buf, (size_t *)NULL);
654                     Buf_Destroy(buf, FALSE);
655
656                     DEBUGF(COND, ("lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
657                            lhs, string, op));
658                     /*
659                      * Null-terminate rhs and perform the comparison.
660                      * t is set to the result.
661                      */
662                     if (*op == '=') {
663                         t = strcmp(lhs, string) ? False : True;
664                     } else {
665                         t = strcmp(lhs, string) ? True : False;
666                     }
667                     free(string);
668                     if (rhs == condExpr) {
669                         if (!qt && *cp == ')')
670                             condExpr = cp;
671                         else
672                             condExpr = cp + 1;
673                     }
674                 } else {
675                     /*
676                      * rhs is either a float or an integer. Convert both the
677                      * lhs and the rhs to a double and compare the two.
678                      */
679                     double      left, right;
680                     char        *string;
681
682                     if (*CondCvtArg(lhs, &left) != '\0')
683                         goto do_string_compare;
684                     if (*rhs == '$') {
685                         size_t len;
686                         Boolean freeIt;
687
688                         string = Var_Parse(rhs, VAR_CMD, doEval, &len, &freeIt);
689                         if (string == var_Error) {
690                             right = 0.0;
691                         } else {
692                             if (*CondCvtArg(string, &right) != '\0') {
693                                 if (freeIt)
694                                     free(string);
695                                 goto do_string_compare;
696                             }
697                             if (freeIt)
698                                 free(string);
699                             if (rhs == condExpr)
700                                 condExpr += len;
701                         }
702                     } else {
703                         char *c = CondCvtArg(rhs, &right);
704                         if (c == rhs)
705                             goto do_string_compare;
706                         if (rhs == condExpr) {
707                             /*
708                              * Skip over the right-hand side
709                              */
710                             condExpr = c;
711                         }
712                     }
713
714                     DEBUGF(COND, ("left = %f, right = %f, op = %.2s\n", left,
715                            right, op));
716                     switch (op[0]) {
717                     case '!':
718                         if (op[1] != '=') {
719                             Parse_Error(PARSE_WARNING,
720                                         "Unknown operator");
721                             goto error;
722                         }
723                         t = (left != right ? True : False);
724                         break;
725                     case '=':
726                         if (op[1] != '=') {
727                             Parse_Error(PARSE_WARNING,
728                                         "Unknown operator");
729                             goto error;
730                         }
731                         t = (left == right ? True : False);
732                         break;
733                     case '<':
734                         if (op[1] == '=') {
735                             t = (left <= right ? True : False);
736                         } else {
737                             t = (left < right ? True : False);
738                         }
739                         break;
740                     case '>':
741                         if (op[1] == '=') {
742                             t = (left >= right ? True : False);
743                         } else {
744                             t = (left > right ? True : False);
745                         }
746                         break;
747                     default:
748                         break;
749                     }
750                 }
751 error:
752                 if (doFree)
753                     free(lhs);
754                 break;
755             }
756             default: {
757                 CondProc        *evalProc;
758                 Boolean         invert = FALSE;
759                 char            *arg;
760                 int             arglen;
761
762                 if (strncmp(condExpr, "defined", 7) == 0) {
763                     /*
764                      * Use CondDoDefined to evaluate the argument and
765                      * CondGetArg to extract the argument from the 'function
766                      * call'.
767                      */
768                     evalProc = CondDoDefined;
769                     condExpr += 7;
770                     arglen = CondGetArg(&condExpr, &arg, "defined", TRUE);
771                     if (arglen == 0) {
772                         condExpr -= 7;
773                         goto use_default;
774                     }
775                 } else if (strncmp(condExpr, "make", 4) == 0) {
776                     /*
777                      * Use CondDoMake to evaluate the argument and
778                      * CondGetArg to extract the argument from the 'function
779                      * call'.
780                      */
781                     evalProc = CondDoMake;
782                     condExpr += 4;
783                     arglen = CondGetArg(&condExpr, &arg, "make", TRUE);
784                     if (arglen == 0) {
785                         condExpr -= 4;
786                         goto use_default;
787                     }
788                 } else if (strncmp(condExpr, "exists", 6) == 0) {
789                     /*
790                      * Use CondDoExists to evaluate the argument and
791                      * CondGetArg to extract the argument from the
792                      * 'function call'.
793                      */
794                     evalProc = CondDoExists;
795                     condExpr += 6;
796                     arglen = CondGetArg(&condExpr, &arg, "exists", TRUE);
797                     if (arglen == 0) {
798                         condExpr -= 6;
799                         goto use_default;
800                     }
801                 } else if (strncmp(condExpr, "empty", 5) == 0) {
802                     /*
803                      * Use Var_Parse to parse the spec in parens and return
804                      * True if the resulting string is empty.
805                      */
806                     size_t length;
807                     Boolean doFree;
808                     char    *val;
809
810                     condExpr += 5;
811
812                     for (arglen = 0;
813                          condExpr[arglen] != '(' && condExpr[arglen] != '\0';
814                          arglen += 1)
815                         continue;
816
817                     if (condExpr[arglen] != '\0') {
818                         val = Var_Parse(&condExpr[arglen - 1], VAR_CMD,
819                                         FALSE, &length, &doFree);
820                         if (val == var_Error) {
821                             t = Err;
822                         } else {
823                             /*
824                              * A variable is empty when it just contains
825                              * spaces... 4/15/92, christos
826                              */
827                             char *p;
828                             for (p = val; *p && isspace((unsigned char)*p); p++)
829                                 continue;
830                             t = (*p == '\0') ? True : False;
831                         }
832                         if (doFree) {
833                             free(val);
834                         }
835                         /*
836                          * Advance condExpr to beyond the closing ). Note that
837                          * we subtract one from arglen + length b/c length
838                          * is calculated from condExpr[arglen - 1].
839                          */
840                         condExpr += arglen + length - 1;
841                     } else {
842                         condExpr -= 5;
843                         goto use_default;
844                     }
845                     break;
846                 } else if (strncmp(condExpr, "target", 6) == 0) {
847                     /*
848                      * Use CondDoTarget to evaluate the argument and
849                      * CondGetArg to extract the argument from the
850                      * 'function call'.
851                      */
852                     evalProc = CondDoTarget;
853                     condExpr += 6;
854                     arglen = CondGetArg(&condExpr, &arg, "target", TRUE);
855                     if (arglen == 0) {
856                         condExpr -= 6;
857                         goto use_default;
858                     }
859                 } else {
860                     /*
861                      * The symbol is itself the argument to the default
862                      * function. We advance condExpr to the end of the symbol
863                      * by hand (the next whitespace, closing paren or
864                      * binary operator) and set to invert the evaluation
865                      * function if condInvert is TRUE.
866                      */
867                 use_default:
868                     invert = condInvert;
869                     evalProc = condDefProc;
870                     arglen = CondGetArg(&condExpr, &arg, "", FALSE);
871                 }
872
873                 /*
874                  * Evaluate the argument using the set function. If invert
875                  * is TRUE, we invert the sense of the function.
876                  */
877                 t = (!doEval || (* evalProc) (arglen, arg) ?
878                      (invert ? False : True) :
879                      (invert ? True : False));
880                 free(arg);
881                 break;
882             }
883         }
884     } else {
885         t = condPushBack;
886         condPushBack = None;
887     }
888     return (t);
889 }
890
891 /*-
892  *-----------------------------------------------------------------------
893  * CondT --
894  *      Parse a single term in the expression. This consists of a terminal
895  *      symbol or Not and a terminal symbol (not including the binary
896  *      operators):
897  *          T -> defined(variable) | make(target) | exists(file) | symbol
898  *          T -> ! T | ( E )
899  *
900  * Results:
901  *      True, False or Err.
902  *
903  * Side Effects:
904  *      Tokens are consumed.
905  *
906  *-----------------------------------------------------------------------
907  */
908 static Token
909 CondT(Boolean doEval)
910 {
911     Token   t;
912
913     t = CondToken(doEval);
914
915     if (t == EndOfFile) {
916         /*
917          * If we reached the end of the expression, the expression
918          * is malformed...
919          */
920         t = Err;
921     } else if (t == LParen) {
922         /*
923          * T -> ( E )
924          */
925         t = CondE(doEval);
926         if (t != Err) {
927             if (CondToken(doEval) != RParen) {
928                 t = Err;
929             }
930         }
931     } else if (t == Not) {
932         t = CondT(doEval);
933         if (t == True) {
934             t = False;
935         } else if (t == False) {
936             t = True;
937         }
938     }
939     return (t);
940 }
941
942 /*-
943  *-----------------------------------------------------------------------
944  * CondF --
945  *      Parse a conjunctive factor (nice name, wot?)
946  *          F -> T && F | T
947  *
948  * Results:
949  *      True, False or Err
950  *
951  * Side Effects:
952  *      Tokens are consumed.
953  *
954  *-----------------------------------------------------------------------
955  */
956 static Token
957 CondF(Boolean doEval)
958 {
959     Token   l, o;
960
961     l = CondT(doEval);
962     if (l != Err) {
963         o = CondToken(doEval);
964
965         if (o == And) {
966             /*
967              * F -> T && F
968              *
969              * If T is False, the whole thing will be False, but we have to
970              * parse the r.h.s. anyway (to throw it away).
971              * If T is True, the result is the r.h.s., be it an Err or no.
972              */
973             if (l == True) {
974                 l = CondF(doEval);
975             } else {
976                  CondF(FALSE);
977             }
978         } else {
979             /*
980              * F -> T
981              */
982             CondPushBack(o);
983         }
984     }
985     return (l);
986 }
987
988 /*-
989  *-----------------------------------------------------------------------
990  * CondE --
991  *      Main expression production.
992  *          E -> F || E | F
993  *
994  * Results:
995  *      True, False or Err.
996  *
997  * Side Effects:
998  *      Tokens are, of course, consumed.
999  *
1000  *-----------------------------------------------------------------------
1001  */
1002 static Token
1003 CondE(Boolean doEval)
1004 {
1005     Token   l, o;
1006
1007     l = CondF(doEval);
1008     if (l != Err) {
1009         o = CondToken(doEval);
1010
1011         if (o == Or) {
1012             /*
1013              * E -> F || E
1014              *
1015              * A similar thing occurs for ||, except that here we make sure
1016              * the l.h.s. is False before we bother to evaluate the r.h.s.
1017              * Once again, if l is False, the result is the r.h.s. and once
1018              * again if l is True, we parse the r.h.s. to throw it away.
1019              */
1020             if (l == False) {
1021                 l = CondE(doEval);
1022             } else {
1023                  CondE(FALSE);
1024             }
1025         } else {
1026             /*
1027              * E -> F
1028              */
1029             CondPushBack(o);
1030         }
1031     }
1032     return (l);
1033 }
1034
1035 /*-
1036  *-----------------------------------------------------------------------
1037  * Cond_Eval --
1038  *      Evaluate the conditional in the passed line. The line
1039  *      looks like this:
1040  *          #<cond-type> <expr>
1041  *      where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1042  *      ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1043  *      and <expr> consists of &&, ||, !, make(target), defined(variable)
1044  *      and parenthetical groupings thereof.
1045  *
1046  * Results:
1047  *      COND_PARSE      if should parse lines after the conditional
1048  *      COND_SKIP       if should skip lines after the conditional
1049  *      COND_INVALID    if not a valid conditional.
1050  *
1051  * Side Effects:
1052  *      None.
1053  *
1054  *-----------------------------------------------------------------------
1055  */
1056 int
1057 Cond_Eval(char *line)
1058 {
1059     struct If       *ifp;
1060     Boolean         isElse;
1061     Boolean         value = FALSE;
1062     int             level;      /* Level at which to report errors. */
1063     int             lineno;
1064
1065     level = PARSE_FATAL;
1066     lineno = curFile.lineno;
1067
1068     for (line++; *line == ' ' || *line == '\t'; line++) {
1069         continue;
1070     }
1071
1072     /*
1073      * Find what type of if we're dealing with. The result is left
1074      * in ifp and isElse is set TRUE if it's an elif line.
1075      */
1076     if (line[0] == 'e' && line[1] == 'l') {
1077         line += 2;
1078         isElse = TRUE;
1079     } else if (strncmp(line, "endif", 5) == 0) {
1080         /*
1081          * End of a conditional section. If skipIfLevel is non-zero, that
1082          * conditional was skipped, so lines following it should also be
1083          * skipped. Hence, we return COND_SKIP. Otherwise, the conditional
1084          * was read so succeeding lines should be parsed (think about it...)
1085          * so we return COND_PARSE, unless this endif isn't paired with
1086          * a decent if.
1087          */
1088         if (skipIfLevel != 0) {
1089             skipIfLevel -= 1;
1090             return (COND_SKIP);
1091         } else {
1092             if (condTop == MAXIF) {
1093                 Parse_Error(level, "if-less endif");
1094                 return (COND_INVALID);
1095             } else {
1096                 skipLine = FALSE;
1097                 condTop += 1;
1098                 return (COND_PARSE);
1099             }
1100         }
1101     } else {
1102         isElse = FALSE;
1103     }
1104
1105     /*
1106      * Figure out what sort of conditional it is -- what its default
1107      * function is, etc. -- by looking in the table of valid "ifs"
1108      */
1109     for (ifp = ifs; ifp->form != NULL; ifp++) {
1110         if (strncmp(ifp->form, line, ifp->formlen) == 0) {
1111             break;
1112         }
1113     }
1114
1115     if (ifp->form == NULL) {
1116         /*
1117          * Nothing fit. If the first word on the line is actually
1118          * "else", it's a valid conditional whose value is the inverse
1119          * of the previous if we parsed.
1120          */
1121         if (isElse && (line[0] == 's') && (line[1] == 'e')) {
1122             if (condTop == MAXIF) {
1123                 Parse_Error(level, "if-less else");
1124                 return (COND_INVALID);
1125             } else if (skipIfLevel == 0) {
1126                 value = !condStack[condTop];
1127                 lineno = condLineno[condTop];
1128             } else {
1129                 return (COND_SKIP);
1130             }
1131         } else {
1132             /*
1133              * Not a valid conditional type. No error...
1134              */
1135             return (COND_INVALID);
1136         }
1137     } else {
1138         if (isElse) {
1139             if (condTop == MAXIF) {
1140                 Parse_Error(level, "if-less elif");
1141                 return (COND_INVALID);
1142             } else if (skipIfLevel != 0) {
1143                 /*
1144                  * If skipping this conditional, just ignore the whole thing.
1145                  * If we don't, the user might be employing a variable that's
1146                  * undefined, for which there's an enclosing ifdef that
1147                  * we're skipping...
1148                  */
1149                 skipIfLineno[skipIfLevel - 1] = lineno;
1150                 return (COND_SKIP);
1151             }
1152         } else if (skipLine) {
1153             /*
1154              * Don't even try to evaluate a conditional that's not an else if
1155              * we're skipping things...
1156              */
1157             skipIfLineno[skipIfLevel] = lineno;
1158             skipIfLevel += 1;
1159             return (COND_SKIP);
1160         }
1161
1162         /*
1163          * Initialize file-global variables for parsing
1164          */
1165         condDefProc = ifp->defProc;
1166         condInvert = ifp->doNot;
1167
1168         line += ifp->formlen;
1169
1170         while (*line == ' ' || *line == '\t') {
1171             line++;
1172         }
1173
1174         condExpr = line;
1175         condPushBack = None;
1176
1177         switch (CondE(TRUE)) {
1178             case True:
1179                 if (CondToken(TRUE) == EndOfFile) {
1180                     value = TRUE;
1181                     break;
1182                 }
1183                 goto err;
1184                 /*FALLTHRU*/
1185             case False:
1186                 if (CondToken(TRUE) == EndOfFile) {
1187                     value = FALSE;
1188                     break;
1189                 }
1190                 /*FALLTHRU*/
1191             case Err:
1192             err:
1193                 Parse_Error(level, "Malformed conditional (%s)",
1194                              line);
1195                 return (COND_INVALID);
1196             default:
1197                 break;
1198         }
1199     }
1200     if (!isElse) {
1201         condTop -= 1;
1202     } else if ((skipIfLevel != 0) || condStack[condTop]) {
1203         /*
1204          * If this is an else-type conditional, it should only take effect
1205          * if its corresponding if was evaluated and FALSE. If its if was
1206          * TRUE or skipped, we return COND_SKIP (and start skipping in case
1207          * we weren't already), leaving the stack unmolested so later elif's
1208          * don't screw up...
1209          */
1210         skipLine = TRUE;
1211         return (COND_SKIP);
1212     }
1213
1214     if (condTop < 0) {
1215         /*
1216          * This is the one case where we can definitely proclaim a fatal
1217          * error. If we don't, we're hosed.
1218          */
1219         Parse_Error(PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
1220         return (COND_INVALID);
1221     } else {
1222         condStack[condTop] = value;
1223         condLineno[condTop] = lineno;
1224         skipLine = !value;
1225         return (value ? COND_PARSE : COND_SKIP);
1226     }
1227 }
1228
1229 /*-
1230  *-----------------------------------------------------------------------
1231  * Cond_End --
1232  *      Make sure everything's clean at the end of a makefile.
1233  *
1234  * Results:
1235  *      None.
1236  *
1237  * Side Effects:
1238  *      Parse_Error will be called if open conditionals are around.
1239  *
1240  *-----------------------------------------------------------------------
1241  */
1242 void
1243 Cond_End(void)
1244 {
1245     int level;
1246
1247     if (condTop != MAXIF) {
1248         Parse_Error(PARSE_FATAL, "%d open conditional%s:",
1249             MAXIF - condTop + skipIfLevel,
1250             MAXIF - condTop + skipIfLevel== 1 ? "" : "s");
1251
1252         for (level = skipIfLevel; level > 0; level--)
1253                 Parse_Error(PARSE_FATAL, "\t%*sat line %d (skipped)",
1254                     MAXIF - condTop + level + 1, "", skipIfLineno[level - 1]);
1255         for (level = condTop; level < MAXIF; level++)
1256                 Parse_Error(PARSE_FATAL, "\t%*sat line %d "
1257                     "(evaluated to %s)", MAXIF - level + skipIfLevel, "",
1258                     condLineno[level], condStack[level] ? "true" : "false");
1259     }
1260     condTop = MAXIF;
1261 }