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

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

CVSweb <webmaster@jp.NetBSD.org>