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