source: trunk/src/kmk/cond.c@ 44

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

emx is kind of working again...

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 31.4 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 t = False;
536 condExpr += strlen(condExpr);
537 break;
538 #endif
539
540
541 #ifdef NMAKE
542 case '"':
543 #endif
544 case '$': {
545 char *lhs;
546 char *rhs;
547 char *op;
548 int varSpecLen;
549 Boolean doFree;
550 #ifdef NMAKE
551 Boolean fQuoted = (*condExpr == '"');
552 if (fQuoted)
553 condExpr++;
554 #endif
555
556 /*
557 * Parse the variable spec and skip over it, saving its
558 * value in lhs.
559 */
560 t = Err;
561 lhs = Var_Parse(condExpr, VAR_CMD, doEval,&varSpecLen,&doFree);
562 #ifdef NMAKE
563 if (lhs == var_Error)
564 {
565 //@todo check if actually parsed correctly.
566 doFree = 0;
567 }
568 #else
569 if (lhs == var_Error) {
570 /*
571 * Even if !doEval, we still report syntax errors, which
572 * is what getting var_Error back with !doEval means.
573 */
574 return(Err);
575 }
576 #endif
577 condExpr += varSpecLen;
578
579 #ifdef NMAKE
580 if ( (fQuoted && *condExpr != '"')
581 || (!fQuoted && !isspace((unsigned char) *condExpr) && strchr("!=><", *condExpr) == NULL)
582 )
583 #else
584 if (!isspace((unsigned char) *condExpr) &&
585 strchr("!=><", *condExpr) == NULL)
586 #endif
587 {
588 Buffer buf;
589 char *cp;
590
591 buf = Buf_Init(0);
592
593 for (cp = lhs; *cp; cp++)
594 Buf_AddByte(buf, (Byte)*cp);
595
596 if (doFree)
597 efree(lhs);
598
599 #ifdef NMAKE
600 for (;*condExpr && (fQuoted ? *condExpr != '"' : !isspace((unsigned char) *condExpr)); condExpr++)
601 #else
602 for (;*condExpr && !isspace((unsigned char) *condExpr); condExpr++)
603 #endif
604 Buf_AddByte(buf, (Byte)*condExpr);
605
606 Buf_AddByte(buf, (Byte)'\0');
607 lhs = (char *)Buf_GetAll(buf, &varSpecLen);
608 Buf_Destroy(buf, FALSE);
609
610 doFree = TRUE;
611 }
612
613 /*
614 * Skip whitespace to get to the operator
615 */
616 #ifdef NMAKE
617 if (fQuoted && *condExpr == '"')
618 condExpr++;
619 #endif
620 while (isspace((unsigned char) *condExpr))
621 condExpr++;
622
623 /*
624 * Make sure the operator is a valid one. If it isn't a
625 * known relational operator, pretend we got a
626 * != 0 comparison.
627 */
628 op = condExpr;
629 switch (*condExpr) {
630 case '!':
631 case '=':
632 case '<':
633 case '>':
634 if (condExpr[1] == '=') {
635 condExpr += 2;
636 } else {
637 condExpr += 1;
638 }
639 break;
640 default:
641 op = "!=";
642 rhs = "0";
643
644 goto do_compare;
645 }
646 while (isspace((unsigned char) *condExpr)) {
647 condExpr++;
648 }
649 if (*condExpr == '\0') {
650 Parse_Error(PARSE_WARNING,
651 "Missing right-hand-side of operator");
652 goto error;
653 }
654 rhs = condExpr;
655do_compare:
656 if (*rhs == '"') {
657 /*
658 * Doing a string comparison. Only allow == and != for
659 * operators.
660 */
661 char *string;
662 char *cp, *cp2;
663 int qt;
664 Buffer buf;
665
666do_string_compare:
667 if (((*op != '!') && (*op != '=')) || (op[1] != '=')) {
668 Parse_Error(PARSE_WARNING,
669 "String comparison operator should be either == or !=");
670 goto error;
671 }
672
673 buf = Buf_Init(0);
674 qt = *rhs == '"' ? 1 : 0;
675
676 for (cp = &rhs[qt];
677 ((qt && (*cp != '"')) ||
678 (!qt && strchr(" \t)", *cp) == NULL)) &&
679 (*cp != '\0'); cp++) {
680 if ((*cp == '\\') && (cp[1] != '\0')) {
681 /*
682 * Backslash escapes things -- skip over next
683 * character, if it exists.
684 */
685 cp++;
686 Buf_AddByte(buf, (Byte)*cp);
687 } else if (*cp == '$') {
688 int len;
689 Boolean freeIt;
690
691 cp2 = Var_Parse(cp, VAR_CMD, doEval,&len, &freeIt);
692 if (cp2 != var_Error) {
693 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
694 if (freeIt) {
695 efree(cp2);
696 }
697 cp += len - 1;
698 } else {
699 Buf_AddByte(buf, (Byte)*cp);
700 }
701 } else {
702 Buf_AddByte(buf, (Byte)*cp);
703 }
704 }
705
706 Buf_AddByte(buf, (Byte)0);
707
708 string = (char *)Buf_GetAll(buf, (int *)0);
709 Buf_Destroy(buf, FALSE);
710
711 if (DEBUG(COND)) {
712 printf("lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
713 lhs, string, op);
714 }
715 /*
716 * Null-terminate rhs and perform the comparison.
717 * t is set to the result.
718 */
719 if (*op == '=') {
720 t = strcmp(lhs, string) ? False : True;
721 } else {
722 t = strcmp(lhs, string) ? True : False;
723 }
724 efree(string);
725 if (rhs == condExpr) {
726 if (!qt && *cp == ')')
727 condExpr = cp;
728 else
729 condExpr = cp + 1;
730 }
731 } else {
732 /*
733 * rhs is either a float or an integer. Convert both the
734 * lhs and the rhs to a double and compare the two.
735 */
736 double left, right;
737 char *string;
738
739 if (*CondCvtArg(lhs, &left) != '\0')
740 goto do_string_compare;
741 if (*rhs == '$') {
742 int len;
743 Boolean freeIt;
744
745 string = Var_Parse(rhs, VAR_CMD, doEval,&len,&freeIt);
746 if (string == var_Error) {
747 right = 0.0;
748 } else {
749 if (*CondCvtArg(string, &right) != '\0') {
750 if (freeIt)
751 efree(string);
752 goto do_string_compare;
753 }
754 if (freeIt)
755 efree(string);
756 if (rhs == condExpr)
757 condExpr += len;
758 }
759 } else {
760 char *c = CondCvtArg(rhs, &right);
761 if (*c != '\0' && !isspace(*c))
762 goto do_string_compare;
763 if (rhs == condExpr) {
764 /*
765 * Skip over the right-hand side
766 */
767 while(!isspace((unsigned char) *condExpr) &&
768 (*condExpr != '\0')) {
769 condExpr++;
770 }
771 }
772 }
773
774 if (DEBUG(COND)) {
775 printf("left = %f, right = %f, op = %.2s\n", left,
776 right, op);
777 }
778 switch(op[0]) {
779 case '!':
780 if (op[1] != '=') {
781 Parse_Error(PARSE_WARNING,
782 "Unknown operator");
783 goto error;
784 }
785 t = (left != right ? True : False);
786 break;
787 case '=':
788 if (op[1] != '=') {
789 Parse_Error(PARSE_WARNING,
790 "Unknown operator");
791 goto error;
792 }
793 t = (left == right ? True : False);
794 break;
795 case '<':
796 if (op[1] == '=') {
797 t = (left <= right ? True : False);
798 } else {
799 t = (left < right ? True : False);
800 }
801 break;
802 case '>':
803 if (op[1] == '=') {
804 t = (left >= right ? True : False);
805 } else {
806 t = (left > right ? True : False);
807 }
808 break;
809 }
810 }
811error:
812 if (doFree)
813 efree(lhs);
814 break;
815 }
816 default: {
817 Boolean (*evalProc) __P((int, char *));
818 Boolean invert = FALSE;
819 char *arg;
820 int arglen;
821
822 if (strncmp (condExpr, "defined", 7) == 0) {
823 /*
824 * Use CondDoDefined to evaluate the argument and
825 * CondGetArg to extract the argument from the 'function
826 * call'.
827 */
828 evalProc = CondDoDefined;
829 condExpr += 7;
830 arglen = CondGetArg (&condExpr, &arg, "defined", TRUE);
831 if (arglen == 0) {
832 condExpr -= 7;
833 goto use_default;
834 }
835 } else if (strncmp (condExpr, "make", 4) == 0) {
836 /*
837 * Use CondDoMake to evaluate the argument and
838 * CondGetArg to extract the argument from the 'function
839 * call'.
840 */
841 evalProc = CondDoMake;
842 condExpr += 4;
843 arglen = CondGetArg (&condExpr, &arg, "make", TRUE);
844 if (arglen == 0) {
845 condExpr -= 4;
846 goto use_default;
847 }
848 } else if (strncmp (condExpr, "exists", 6) == 0) {
849 /*
850 * Use CondDoExists to evaluate the argument and
851 * CondGetArg to extract the argument from the
852 * 'function call'.
853 */
854 evalProc = CondDoExists;
855 condExpr += 6;
856 arglen = CondGetArg(&condExpr, &arg, "exists", TRUE);
857 if (arglen == 0) {
858 condExpr -= 6;
859 goto use_default;
860 }
861 } else if (strncmp(condExpr, "empty", 5) == 0) {
862 /*
863 * Use Var_Parse to parse the spec in parens and return
864 * True if the resulting string is empty.
865 */
866 int length;
867 Boolean doFree;
868 char *val;
869
870 condExpr += 5;
871
872 for (arglen = 0;
873 condExpr[arglen] != '(' && condExpr[arglen] != '\0';
874 arglen += 1)
875 continue;
876
877 if (condExpr[arglen] != '\0') {
878 val = Var_Parse(&condExpr[arglen - 1], VAR_CMD,
879 doEval, &length, &doFree);
880 if (val == var_Error) {
881 t = Err;
882 } else {
883 /*
884 * A variable is empty when it just contains
885 * spaces... 4/15/92, christos
886 */
887 char *p;
888 for (p = val; *p && isspace((unsigned char)*p); p++)
889 continue;
890 t = (*p == '\0') ? True : False;
891 }
892 if (doFree) {
893 efree(val);
894 }
895 /*
896 * Advance condExpr to beyond the closing ). Note that
897 * we subtract one from arglen + length b/c length
898 * is calculated from condExpr[arglen - 1].
899 */
900 condExpr += arglen + length - 1;
901 } else {
902 condExpr -= 5;
903 goto use_default;
904 }
905 break;
906 } else if (strncmp (condExpr, "target", 6) == 0) {
907 /*
908 * Use CondDoTarget to evaluate the argument and
909 * CondGetArg to extract the argument from the
910 * 'function call'.
911 */
912 evalProc = CondDoTarget;
913 condExpr += 6;
914 arglen = CondGetArg(&condExpr, &arg, "target", TRUE);
915 if (arglen == 0) {
916 condExpr -= 6;
917 goto use_default;
918 }
919 } else {
920 /*
921 * The symbol is itself the argument to the default
922 * function. We advance condExpr to the end of the symbol
923 * by hand (the next whitespace, closing paren or
924 * binary operator) and set to invert the evaluation
925 * function if condInvert is TRUE.
926 */
927 use_default:
928 invert = condInvert;
929 evalProc = condDefProc;
930 arglen = CondGetArg(&condExpr, &arg, "", FALSE);
931 }
932
933 /*
934 * Evaluate the argument using the set function. If invert
935 * is TRUE, we invert the sense of the function.
936 */
937 t = (!doEval || (* evalProc) (arglen, arg) ?
938 (invert ? False : True) :
939 (invert ? True : False));
940 efree(arg);
941 break;
942 }
943 }
944 } else {
945 t = condPushBack;
946 condPushBack = None;
947 }
948 return (t);
949}
950
951
952/*-
953 *-----------------------------------------------------------------------
954 * CondT --
955 * Parse a single term in the expression. This consists of a terminal
956 * symbol or Not and a terminal symbol (not including the binary
957 * operators):
958 * T -> defined(variable) | make(target) | exists(file) | symbol
959 * T -> ! T | ( E )
960 *
961 * Results:
962 * True, False or Err.
963 *
964 * Side Effects:
965 * Tokens are consumed.
966 *
967 *-----------------------------------------------------------------------
968 */
969static Token
970CondT(doEval)
971 Boolean doEval;
972{
973 Token t;
974
975 t = CondToken(doEval);
976
977 if (t == EndOfFile) {
978 /*
979 * If we reached the end of the expression, the expression
980 * is malformed...
981 */
982 t = Err;
983 } else if (t == LParen) {
984 /*
985 * T -> ( E )
986 */
987 t = CondE(doEval);
988 if (t != Err) {
989 if (CondToken(doEval) != RParen) {
990 t = Err;
991 }
992 }
993 } else if (t == Not) {
994 t = CondT(doEval);
995 if (t == True) {
996 t = False;
997 } else if (t == False) {
998 t = True;
999 }
1000 }
1001 return (t);
1002}
1003
1004
1005/*-
1006 *-----------------------------------------------------------------------
1007 * CondF --
1008 * Parse a conjunctive factor (nice name, wot?)
1009 * F -> T && F | T
1010 *
1011 * Results:
1012 * True, False or Err
1013 *
1014 * Side Effects:
1015 * Tokens are consumed.
1016 *
1017 *-----------------------------------------------------------------------
1018 */
1019static Token
1020CondF(doEval)
1021 Boolean doEval;
1022{
1023 Token l, o;
1024
1025 l = CondT(doEval);
1026 if (l != Err) {
1027 o = CondToken(doEval);
1028
1029 if (o == And) {
1030 /*
1031 * F -> T && F
1032 *
1033 * If T is False, the whole thing will be False, but we have to
1034 * parse the r.h.s. anyway (to throw it away).
1035 * If T is True, the result is the r.h.s., be it an Err or no.
1036 */
1037 if (l == True) {
1038 l = CondF(doEval);
1039 } else {
1040 (void) CondF(FALSE);
1041 }
1042 } else {
1043 /*
1044 * F -> T
1045 */
1046 CondPushBack (o);
1047 }
1048 }
1049 return (l);
1050}
1051
1052
1053/*-
1054 *-----------------------------------------------------------------------
1055 * CondE --
1056 * Main expression production.
1057 * E -> F || E | F
1058 *
1059 * Results:
1060 * True, False or Err.
1061 *
1062 * Side Effects:
1063 * Tokens are, of course, consumed.
1064 *
1065 *-----------------------------------------------------------------------
1066 */
1067static Token
1068CondE(doEval)
1069 Boolean doEval;
1070{
1071 Token l, o;
1072
1073 l = CondF(doEval);
1074 if (l != Err) {
1075 o = CondToken(doEval);
1076
1077 if (o == Or) {
1078 /*
1079 * E -> F || E
1080 *
1081 * A similar thing occurs for ||, except that here we make sure
1082 * the l.h.s. is False before we bother to evaluate the r.h.s.
1083 * Once again, if l is False, the result is the r.h.s. and once
1084 * again if l is True, we parse the r.h.s. to throw it away.
1085 */
1086 if (l == False) {
1087 l = CondE(doEval);
1088 } else {
1089 (void) CondE(FALSE);
1090 }
1091 } else {
1092 /*
1093 * E -> F
1094 */
1095 CondPushBack (o);
1096 }
1097 }
1098 return (l);
1099}
1100
1101
1102/*-
1103 *-----------------------------------------------------------------------
1104 * Cond_Eval --
1105 * Evaluate the conditional in the passed line. The line
1106 * looks like this:
1107 * #<cond-type> <expr>
1108 * where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1109 * ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1110 * and <expr> consists of &&, ||, !, make(target), defined(variable)
1111 * and parenthetical groupings thereof.
1112 *
1113 * Results:
1114 * COND_PARSE if should parse lines after the conditional
1115 * COND_SKIP if should skip lines after the conditional
1116 * COND_INVALID if not a valid conditional.
1117 *
1118 * Side Effects:
1119 * None.
1120 *
1121 *-----------------------------------------------------------------------
1122 */
1123int
1124Cond_Eval (line)
1125 char *line; /* Line to parse */
1126{
1127 struct If *ifp;
1128 Boolean isElse;
1129 Boolean value = FALSE;
1130 int level; /* Level at which to report errors. */
1131
1132 level = PARSE_FATAL;
1133
1134 for (line++; *line == ' ' || *line == '\t'; line++) {
1135 continue;
1136 }
1137
1138 /*
1139 * Find what type of if we're dealing with. The result is left
1140 * in ifp and isElse is set TRUE if it's an elif line.
1141 */
1142 if (line[0] == 'e' && line[1] == 'l') {
1143 line += 2;
1144 isElse = TRUE;
1145 } else if (strncmp (line, "endif", 5) == 0) {
1146 /*
1147 * End of a conditional section. If skipIfLevel is non-zero, that
1148 * conditional was skipped, so lines following it should also be
1149 * skipped. Hence, we return COND_SKIP. Otherwise, the conditional
1150 * was read so succeeding lines should be parsed (think about it...)
1151 * so we return COND_PARSE, unless this endif isn't paired with
1152 * a decent if.
1153 */
1154 if (skipIfLevel != 0) {
1155 skipIfLevel -= 1;
1156 return (COND_SKIP);
1157 } else {
1158 if (condTop == MAXIF) {
1159 Parse_Error (level, "if-less endif");
1160 return (COND_INVALID);
1161 } else {
1162 skipLine = FALSE;
1163 condTop += 1;
1164 return (COND_PARSE);
1165 }
1166 }
1167 } else {
1168 isElse = FALSE;
1169 }
1170
1171 /*
1172 * Figure out what sort of conditional it is -- what its default
1173 * function is, etc. -- by looking in the table of valid "ifs"
1174 */
1175 for (ifp = ifs; ifp->form != (char *)0; ifp++) {
1176 if (strncmp (ifp->form, line, ifp->formlen) == 0) {
1177 break;
1178 }
1179 }
1180
1181 if (ifp->form == (char *) 0) {
1182 /*
1183 * Nothing fit. If the first word on the line is actually
1184 * "else", it's a valid conditional whose value is the inverse
1185 * of the previous if we parsed.
1186 */
1187 if (isElse && (line[0] == 's') && (line[1] == 'e')) {
1188 if (condTop == MAXIF) {
1189 Parse_Error (level, "if-less else");
1190 return (COND_INVALID);
1191 } else if (skipIfLevel == 0) {
1192 value = !condStack[condTop];
1193 } else {
1194 return (COND_SKIP);
1195 }
1196 } else {
1197 /*
1198 * Not a valid conditional type. No error...
1199 */
1200 return (COND_INVALID);
1201 }
1202 } else {
1203 if (isElse) {
1204 if (condTop == MAXIF) {
1205 Parse_Error (level, "if-less elif");
1206 return (COND_INVALID);
1207 } else if (skipIfLevel != 0) {
1208 /*
1209 * If skipping this conditional, just ignore the whole thing.
1210 * If we don't, the user might be employing a variable that's
1211 * undefined, for which there's an enclosing ifdef that
1212 * we're skipping...
1213 */
1214 return(COND_SKIP);
1215 }
1216 } else if (skipLine) {
1217 /*
1218 * Don't even try to evaluate a conditional that's not an else if
1219 * we're skipping things...
1220 */
1221 skipIfLevel += 1;
1222 return(COND_SKIP);
1223 }
1224
1225 /*
1226 * Initialize file-global variables for parsing
1227 */
1228 condDefProc = ifp->defProc;
1229 condInvert = ifp->doNot;
1230
1231 line += ifp->formlen;
1232
1233 while (*line == ' ' || *line == '\t') {
1234 line++;
1235 }
1236
1237 condExpr = line;
1238 condPushBack = None;
1239
1240 switch (CondE(TRUE)) {
1241 case True:
1242 if (CondToken(TRUE) == EndOfFile) {
1243 value = TRUE;
1244 break;
1245 }
1246 goto err;
1247 /*FALLTHRU*/
1248 case False:
1249 if (CondToken(TRUE) == EndOfFile) {
1250 value = FALSE;
1251 break;
1252 }
1253 /*FALLTHRU*/
1254 case Err:
1255 err:
1256 Parse_Error (level, "Malformed conditional (%s)",
1257 line);
1258 return (COND_INVALID);
1259 default:
1260 break;
1261 }
1262 }
1263 if (!isElse) {
1264 condTop -= 1;
1265 } else if ((skipIfLevel != 0) || condStack[condTop]) {
1266 /*
1267 * If this is an else-type conditional, it should only take effect
1268 * if its corresponding if was evaluated and FALSE. If its if was
1269 * TRUE or skipped, we return COND_SKIP (and start skipping in case
1270 * we weren't already), leaving the stack unmolested so later elif's
1271 * don't screw up...
1272 */
1273 skipLine = TRUE;
1274 return (COND_SKIP);
1275 }
1276
1277 if (condTop < 0) {
1278 /*
1279 * This is the one case where we can definitely proclaim a fatal
1280 * error. If we don't, we're hosed.
1281 */
1282 Parse_Error (PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
1283 return (COND_INVALID);
1284 } else {
1285 condStack[condTop] = value;
1286 skipLine = !value;
1287 return (value ? COND_PARSE : COND_SKIP);
1288 }
1289}
1290
1291
1292/*-
1293 *-----------------------------------------------------------------------
1294 * Cond_End --
1295 * Make sure everything's clean at the end of a makefile.
1296 *
1297 * Results:
1298 * None.
1299 *
1300 * Side Effects:
1301 * Parse_Error will be called if open conditionals are around.
1302 *
1303 *-----------------------------------------------------------------------
1304 */
1305void
1306Cond_End()
1307{
1308 if (condTop != MAXIF) {
1309 Parse_Error(PARSE_FATAL, "%d open conditional%s", MAXIF-condTop,
1310 MAXIF-condTop == 1 ? "" : "s");
1311 }
1312 condTop = MAXIF;
1313}
Note: See TracBrowser for help on using the repository browser.