[BACK]Return to cond.c CVS log [TXT][DIR] Up to [cvs.NetBSD.org] / src / usr.bin / make

Annotation of src/usr.bin/make/cond.c, Revision 1.26

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

CVSweb <webmaster@jp.NetBSD.org>