VirtualBox

source: kBuild/branches/FREEBSD/src/kmk/cond.c@ 10

Last change on this file since 10 was 10, checked in by (none), 23 years ago

This commit was manufactured by cvs2svn to create branch 'FREEBSD'.

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