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