VirtualBox

source: kBuild/trunk/src/kmk/cond.c@ 45

Last change on this file since 45 was 45, checked in by bird, 22 years ago

KMK changes..

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette