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

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

CVSweb <webmaster@jp.NetBSD.org>