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