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