[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.57

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

CVSweb <webmaster@jp.NetBSD.org>