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