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