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