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