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