[BACK]Return to apropos_db.c CVS log [TXT][DIR] Up to [cvsweb.bsd.lv] / mandoc

Annotation of mandoc/apropos_db.c, Revision 1.32.2.1

1.32.2.1! schwarze    1: /*     $Id: apropos_db.c,v 1.32 2012/03/25 00:48:47 kristaps Exp $ */
1.1       schwarze    2: /*
1.31      kristaps    3:  * Copyright (c) 2011, 2012 Kristaps Dzonsons <kristaps@bsd.lv>
1.3       schwarze    4:  * Copyright (c) 2011 Ingo Schwarze <schwarze@openbsd.org>
1.1       schwarze    5:  *
                      6:  * Permission to use, copy, modify, and distribute this software for any
                      7:  * purpose with or without fee is hereby granted, provided that the above
                      8:  * copyright notice and this permission notice appear in all copies.
                      9:  *
                     10:  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
                     11:  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
                     12:  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
                     13:  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
                     14:  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
                     15:  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
                     16:  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
                     17:  */
1.19      kristaps   18: #ifdef HAVE_CONFIG_H
                     19: #include "config.h"
                     20: #endif
                     21:
1.32      kristaps   22: #include <sys/param.h>
                     23:
1.1       schwarze   24: #include <assert.h>
                     25: #include <fcntl.h>
                     26: #include <regex.h>
                     27: #include <stdarg.h>
1.6       kristaps   28: #include <stdint.h>
1.1       schwarze   29: #include <stdlib.h>
                     30: #include <string.h>
1.8       kristaps   31: #include <unistd.h>
1.1       schwarze   32:
1.19      kristaps   33: #if defined(__linux__)
                     34: # include <endian.h>
1.1       schwarze   35: # include <db_185.h>
1.19      kristaps   36: #elif defined(__APPLE__)
                     37: # include <libkern/OSByteOrder.h>
                     38: # include <db.h>
1.1       schwarze   39: #else
1.32.2.1! schwarze   40: # include <sys/endian.h>
1.1       schwarze   41: # include <db.h>
                     42: #endif
                     43:
1.2       schwarze   44: #include "mandocdb.h"
1.1       schwarze   45: #include "apropos_db.h"
                     46: #include "mandoc.h"
                     47:
1.30      kristaps   48: #define        RESFREE(_x) \
                     49:        do { \
                     50:                free((_x)->file); \
                     51:                free((_x)->cat); \
                     52:                free((_x)->title); \
                     53:                free((_x)->arch); \
                     54:                free((_x)->desc); \
                     55:                free((_x)->matches); \
                     56:        } while (/*CONSTCOND*/0)
1.5       kristaps   57:
1.1       schwarze   58: struct expr {
1.5       kristaps   59:        int              regex; /* is regex? */
                     60:        int              index; /* index in match array */
1.6       kristaps   61:        uint64_t         mask; /* type-mask */
1.5       kristaps   62:        int              and; /* is rhs of logical AND? */
                     63:        char            *v; /* search value */
                     64:        regex_t          re; /* compiled re, if regex */
                     65:        struct expr     *next; /* next in sequence */
                     66:        struct expr     *subexpr;
1.1       schwarze   67: };
                     68:
                     69: struct type {
1.6       kristaps   70:        uint64_t         mask;
1.1       schwarze   71:        const char      *name;
                     72: };
                     73:
1.8       kristaps   74: struct rectree {
1.30      kristaps   75:        struct res      *node; /* record array for dir tree */
1.8       kristaps   76:        int              len; /* length of record array */
                     77: };
                     78:
1.1       schwarze   79: static const struct type types[] = {
1.7       kristaps   80:        { TYPE_An, "An" },
                     81:        { TYPE_Ar, "Ar" },
                     82:        { TYPE_At, "At" },
                     83:        { TYPE_Bsx, "Bsx" },
                     84:        { TYPE_Bx, "Bx" },
                     85:        { TYPE_Cd, "Cd" },
                     86:        { TYPE_Cm, "Cm" },
                     87:        { TYPE_Dv, "Dv" },
                     88:        { TYPE_Dx, "Dx" },
                     89:        { TYPE_Em, "Em" },
                     90:        { TYPE_Er, "Er" },
                     91:        { TYPE_Ev, "Ev" },
                     92:        { TYPE_Fa, "Fa" },
                     93:        { TYPE_Fl, "Fl" },
                     94:        { TYPE_Fn, "Fn" },
                     95:        { TYPE_Fn, "Fo" },
                     96:        { TYPE_Ft, "Ft" },
                     97:        { TYPE_Fx, "Fx" },
                     98:        { TYPE_Ic, "Ic" },
                     99:        { TYPE_In, "In" },
                    100:        { TYPE_Lb, "Lb" },
                    101:        { TYPE_Li, "Li" },
                    102:        { TYPE_Lk, "Lk" },
                    103:        { TYPE_Ms, "Ms" },
                    104:        { TYPE_Mt, "Mt" },
                    105:        { TYPE_Nd, "Nd" },
                    106:        { TYPE_Nm, "Nm" },
                    107:        { TYPE_Nx, "Nx" },
                    108:        { TYPE_Ox, "Ox" },
                    109:        { TYPE_Pa, "Pa" },
                    110:        { TYPE_Rs, "Rs" },
                    111:        { TYPE_Sh, "Sh" },
                    112:        { TYPE_Ss, "Ss" },
                    113:        { TYPE_St, "St" },
                    114:        { TYPE_Sy, "Sy" },
                    115:        { TYPE_Tn, "Tn" },
                    116:        { TYPE_Va, "Va" },
                    117:        { TYPE_Va, "Vt" },
                    118:        { TYPE_Xr, "Xr" },
1.25      kristaps  119:        { UINT64_MAX, "any" },
1.1       schwarze  120:        { 0, NULL }
                    121: };
                    122:
                    123: static DB      *btree_open(void);
1.17      kristaps  124: static int      btree_read(const DBT *, const DBT *,
1.28      schwarze  125:                        const struct mchars *,
                    126:                        uint64_t *, recno_t *, char **);
1.5       kristaps  127: static int      expreval(const struct expr *, int *);
1.12      schwarze  128: static void     exprexec(const struct expr *,
1.30      kristaps  129:                        const char *, uint64_t, struct res *);
1.12      schwarze  130: static int      exprmark(const struct expr *,
1.6       kristaps  131:                        const char *, uint64_t, int *);
1.5       kristaps  132: static struct expr *exprexpr(int, char *[], int *, int *, size_t *);
                    133: static struct expr *exprterm(char *, int);
1.1       schwarze  134: static DB      *index_open(void);
1.11      kristaps  135: static int      index_read(const DBT *, const DBT *, int,
1.30      kristaps  136:                        const struct mchars *, struct res *);
1.1       schwarze  137: static void     norm_string(const char *,
                    138:                        const struct mchars *, char **);
                    139: static size_t   norm_utf8(unsigned int, char[7]);
1.8       kristaps  140: static int      single_search(struct rectree *, const struct opts *,
                    141:                        const struct expr *, size_t terms,
1.11      kristaps  142:                        struct mchars *, int);
1.1       schwarze  143:
                    144: /*
                    145:  * Open the keyword mandoc-db database.
                    146:  */
                    147: static DB *
                    148: btree_open(void)
                    149: {
                    150:        BTREEINFO        info;
                    151:        DB              *db;
                    152:
                    153:        memset(&info, 0, sizeof(BTREEINFO));
1.29      kristaps  154:        info.lorder = 4321;
1.1       schwarze  155:        info.flags = R_DUP;
                    156:
1.2       schwarze  157:        db = dbopen(MANDOC_DB, O_RDONLY, 0, DB_BTREE, &info);
1.12      schwarze  158:        if (NULL != db)
1.1       schwarze  159:                return(db);
                    160:
                    161:        return(NULL);
                    162: }
                    163:
                    164: /*
                    165:  * Read a keyword from the database and normalise it.
                    166:  * Return 0 if the database is insane, else 1.
                    167:  */
                    168: static int
1.28      schwarze  169: btree_read(const DBT *k, const DBT *v, const struct mchars *mc,
                    170:                uint64_t *mask, recno_t *rec, char **buf)
1.1       schwarze  171: {
1.28      schwarze  172:        uint64_t         vbuf[2];
1.1       schwarze  173:
1.17      kristaps  174:        /* Are our sizes sane? */
1.28      schwarze  175:        if (k->size < 2 || sizeof(vbuf) != v->size)
1.17      kristaps  176:                return(0);
1.6       kristaps  177:
1.17      kristaps  178:        /* Is our string nil-terminated? */
                    179:        if ('\0' != ((const char *)k->data)[(int)k->size - 1])
1.1       schwarze  180:                return(0);
                    181:
1.17      kristaps  182:        norm_string((const char *)k->data, mc, buf);
1.28      schwarze  183:        memcpy(vbuf, v->data, v->size);
                    184:        *mask = betoh64(vbuf[0]);
                    185:        *rec  = betoh64(vbuf[1]);
1.1       schwarze  186:        return(1);
                    187: }
                    188:
                    189: /*
                    190:  * Take a Unicode codepoint and produce its UTF-8 encoding.
                    191:  * This isn't the best way to do this, but it works.
1.12      schwarze  192:  * The magic numbers are from the UTF-8 packaging.
1.1       schwarze  193:  * They're not as scary as they seem: read the UTF-8 spec for details.
                    194:  */
                    195: static size_t
                    196: norm_utf8(unsigned int cp, char out[7])
                    197: {
1.26      kristaps  198:        int              rc;
1.1       schwarze  199:
                    200:        rc = 0;
                    201:
                    202:        if (cp <= 0x0000007F) {
                    203:                rc = 1;
                    204:                out[0] = (char)cp;
                    205:        } else if (cp <= 0x000007FF) {
                    206:                rc = 2;
                    207:                out[0] = (cp >> 6  & 31) | 192;
                    208:                out[1] = (cp       & 63) | 128;
                    209:        } else if (cp <= 0x0000FFFF) {
                    210:                rc = 3;
                    211:                out[0] = (cp >> 12 & 15) | 224;
                    212:                out[1] = (cp >> 6  & 63) | 128;
                    213:                out[2] = (cp       & 63) | 128;
                    214:        } else if (cp <= 0x001FFFFF) {
                    215:                rc = 4;
                    216:                out[0] = (cp >> 18 & 7) | 240;
                    217:                out[1] = (cp >> 12 & 63) | 128;
                    218:                out[2] = (cp >> 6  & 63) | 128;
                    219:                out[3] = (cp       & 63) | 128;
                    220:        } else if (cp <= 0x03FFFFFF) {
                    221:                rc = 5;
                    222:                out[0] = (cp >> 24 & 3) | 248;
                    223:                out[1] = (cp >> 18 & 63) | 128;
                    224:                out[2] = (cp >> 12 & 63) | 128;
                    225:                out[3] = (cp >> 6  & 63) | 128;
                    226:                out[4] = (cp       & 63) | 128;
                    227:        } else if (cp <= 0x7FFFFFFF) {
                    228:                rc = 6;
                    229:                out[0] = (cp >> 30 & 1) | 252;
                    230:                out[1] = (cp >> 24 & 63) | 128;
                    231:                out[2] = (cp >> 18 & 63) | 128;
                    232:                out[3] = (cp >> 12 & 63) | 128;
                    233:                out[4] = (cp >> 6  & 63) | 128;
                    234:                out[5] = (cp       & 63) | 128;
                    235:        } else
                    236:                return(0);
                    237:
                    238:        out[rc] = '\0';
1.26      kristaps  239:        return((size_t)rc);
1.1       schwarze  240: }
                    241:
                    242: /*
                    243:  * Normalise strings from the index and database.
                    244:  * These strings are escaped as defined by mandoc_char(7) along with
                    245:  * other goop in mandoc.h (e.g., soft hyphens).
                    246:  * This function normalises these into a nice UTF-8 string.
                    247:  * Returns 0 if the database is fucked.
                    248:  */
                    249: static void
                    250: norm_string(const char *val, const struct mchars *mc, char **buf)
                    251: {
                    252:        size_t            sz, bsz;
                    253:        char              utfbuf[7];
                    254:        const char       *seq, *cpp;
                    255:        int               len, u, pos;
                    256:        enum mandoc_esc   esc;
1.12      schwarze  257:        static const char res[] = { '\\', '\t',
1.1       schwarze  258:                                ASCII_NBRSP, ASCII_HYPH, '\0' };
                    259:
                    260:        /* Pre-allocate by the length of the input */
                    261:
                    262:        bsz = strlen(val) + 1;
                    263:        *buf = mandoc_realloc(*buf, bsz);
                    264:        pos = 0;
                    265:
                    266:        while ('\0' != *val) {
                    267:                /*
                    268:                 * Halt on the first escape sequence.
                    269:                 * This also halts on the end of string, in which case
                    270:                 * we just copy, fallthrough, and exit the loop.
                    271:                 */
                    272:                if ((sz = strcspn(val, res)) > 0) {
                    273:                        memcpy(&(*buf)[pos], val, sz);
                    274:                        pos += (int)sz;
                    275:                        val += (int)sz;
                    276:                }
                    277:
                    278:                if (ASCII_HYPH == *val) {
                    279:                        (*buf)[pos++] = '-';
                    280:                        val++;
                    281:                        continue;
                    282:                } else if ('\t' == *val || ASCII_NBRSP == *val) {
                    283:                        (*buf)[pos++] = ' ';
                    284:                        val++;
                    285:                        continue;
                    286:                } else if ('\\' != *val)
                    287:                        break;
                    288:
                    289:                /* Read past the slash. */
                    290:
                    291:                val++;
                    292:                u = 0;
                    293:
                    294:                /*
                    295:                 * Parse the escape sequence and see if it's a
                    296:                 * predefined character or special character.
                    297:                 */
                    298:
                    299:                esc = mandoc_escape(&val, &seq, &len);
                    300:                if (ESCAPE_ERROR == esc)
                    301:                        break;
                    302:
1.12      schwarze  303:                /*
1.1       schwarze  304:                 * XXX - this just does UTF-8, but we need to know
                    305:                 * beforehand whether we should do text substitution.
                    306:                 */
                    307:
                    308:                switch (esc) {
                    309:                case (ESCAPE_SPECIAL):
                    310:                        if (0 != (u = mchars_spec2cp(mc, seq, len)))
                    311:                                break;
                    312:                        /* FALLTHROUGH */
                    313:                default:
                    314:                        continue;
                    315:                }
                    316:
                    317:                /*
                    318:                 * If we have a Unicode codepoint, try to convert that
                    319:                 * to a UTF-8 byte string.
                    320:                 */
                    321:
                    322:                cpp = utfbuf;
                    323:                if (0 == (sz = norm_utf8(u, utfbuf)))
                    324:                        continue;
                    325:
                    326:                /* Copy the rendered glyph into the stream. */
                    327:
                    328:                sz = strlen(cpp);
                    329:                bsz += sz;
                    330:
                    331:                *buf = mandoc_realloc(*buf, bsz);
                    332:
                    333:                memcpy(&(*buf)[pos], cpp, sz);
                    334:                pos += (int)sz;
                    335:        }
                    336:
                    337:        (*buf)[pos] = '\0';
                    338: }
                    339:
                    340: /*
                    341:  * Open the filename-index mandoc-db database.
                    342:  * Returns NULL if opening failed.
                    343:  */
                    344: static DB *
                    345: index_open(void)
                    346: {
                    347:        DB              *db;
                    348:
1.2       schwarze  349:        db = dbopen(MANDOC_IDX, O_RDONLY, 0, DB_RECNO, NULL);
1.1       schwarze  350:        if (NULL != db)
                    351:                return(db);
                    352:
                    353:        return(NULL);
                    354: }
                    355:
                    356: /*
                    357:  * Safely unpack from an index file record into the structure.
                    358:  * Returns 1 if an entry was unpacked, 0 if the database is insane.
                    359:  */
                    360: static int
1.11      kristaps  361: index_read(const DBT *key, const DBT *val, int index,
1.30      kristaps  362:                const struct mchars *mc, struct res *rec)
1.1       schwarze  363: {
                    364:        size_t           left;
                    365:        char            *np, *cp;
1.24      kristaps  366:        char             type;
1.1       schwarze  367:
                    368: #define        INDEX_BREAD(_dst) \
                    369:        do { \
                    370:                if (NULL == (np = memchr(cp, '\0', left))) \
                    371:                        return(0); \
                    372:                norm_string(cp, mc, &(_dst)); \
                    373:                left -= (np - cp) + 1; \
                    374:                cp = np + 1; \
                    375:        } while (/* CONSTCOND */ 0)
                    376:
1.24      kristaps  377:        if (0 == (left = val->size))
                    378:                return(0);
1.1       schwarze  379:
1.24      kristaps  380:        cp = val->data;
1.27      schwarze  381:        assert(sizeof(recno_t) == key->size);
1.30      kristaps  382:        memcpy(&rec->rec, key->data, key->size);
                    383:        rec->volume = index;
1.1       schwarze  384:
1.24      kristaps  385:        if ('d' == (type = *cp++))
1.30      kristaps  386:                rec->type = RESTYPE_MDOC;
1.24      kristaps  387:        else if ('a' == type)
1.30      kristaps  388:                rec->type = RESTYPE_MAN;
1.24      kristaps  389:        else if ('c' == type)
1.30      kristaps  390:                rec->type = RESTYPE_CAT;
1.24      kristaps  391:        else
                    392:                return(0);
                    393:
                    394:        left--;
1.30      kristaps  395:        INDEX_BREAD(rec->file);
                    396:        INDEX_BREAD(rec->cat);
                    397:        INDEX_BREAD(rec->title);
                    398:        INDEX_BREAD(rec->arch);
                    399:        INDEX_BREAD(rec->desc);
1.1       schwarze  400:        return(1);
                    401: }
                    402:
                    403: /*
1.10      kristaps  404:  * Search mandocdb databases in paths for expression "expr".
1.1       schwarze  405:  * Filter out by "opts".
                    406:  * Call "res" with the results, which may be zero.
1.5       kristaps  407:  * Return 0 if there was a database error, else return 1.
1.1       schwarze  408:  */
1.5       kristaps  409: int
1.10      kristaps  410: apropos_search(int pathsz, char **paths, const struct opts *opts,
1.12      schwarze  411:                const struct expr *expr, size_t terms, void *arg,
1.30      kristaps  412:                size_t *sz, struct res **resp,
1.5       kristaps  413:                void (*res)(struct res *, size_t, void *))
1.1       schwarze  414: {
1.8       kristaps  415:        struct rectree   tree;
                    416:        struct mchars   *mc;
1.30      kristaps  417:        int              i, rc;
1.8       kristaps  418:
                    419:        memset(&tree, 0, sizeof(struct rectree));
                    420:
1.10      kristaps  421:        rc = 0;
1.8       kristaps  422:        mc = mchars_alloc();
1.30      kristaps  423:        *sz = 0;
                    424:        *resp = NULL;
1.8       kristaps  425:
1.10      kristaps  426:        /*
                    427:         * Main loop.  Change into the directory containing manpage
                    428:         * databases.  Run our expession over each database in the set.
                    429:         */
                    430:
                    431:        for (i = 0; i < pathsz; i++) {
1.32      kristaps  432:                assert('/' == paths[i][0]);
1.10      kristaps  433:                if (chdir(paths[i]))
1.8       kristaps  434:                        continue;
1.30      kristaps  435:                if (single_search(&tree, opts, expr, terms, mc, i))
                    436:                        continue;
                    437:
                    438:                resfree(tree.node, tree.len);
                    439:                mchars_free(mc);
                    440:                return(0);
1.8       kristaps  441:        }
                    442:
1.30      kristaps  443:        (*res)(tree.node, tree.len, arg);
                    444:        *sz = tree.len;
                    445:        *resp = tree.node;
1.8       kristaps  446:        mchars_free(mc);
1.30      kristaps  447:        return(1);
1.8       kristaps  448: }
                    449:
                    450: static int
                    451: single_search(struct rectree *tree, const struct opts *opts,
                    452:                const struct expr *expr, size_t terms,
1.11      kristaps  453:                struct mchars *mc, int vol)
1.8       kristaps  454: {
                    455:        int              root, leaf, ch;
1.1       schwarze  456:        DBT              key, val;
                    457:        DB              *btree, *idx;
                    458:        char            *buf;
1.30      kristaps  459:        struct res      *rs;
                    460:        struct res       r;
1.28      schwarze  461:        uint64_t         mask;
                    462:        recno_t          rec;
1.1       schwarze  463:
                    464:        root    = -1;
                    465:        leaf    = -1;
                    466:        btree   = NULL;
                    467:        idx     = NULL;
                    468:        buf     = NULL;
1.8       kristaps  469:        rs      = tree->node;
1.1       schwarze  470:
1.30      kristaps  471:        memset(&r, 0, sizeof(struct res));
1.1       schwarze  472:
1.12      schwarze  473:        if (NULL == (btree = btree_open()))
1.10      kristaps  474:                return(1);
1.1       schwarze  475:
1.8       kristaps  476:        if (NULL == (idx = index_open())) {
                    477:                (*btree->close)(btree);
1.10      kristaps  478:                return(1);
1.8       kristaps  479:        }
1.1       schwarze  480:
                    481:        while (0 == (ch = (*btree->seq)(btree, &key, &val, R_NEXT))) {
1.28      schwarze  482:                if ( ! btree_read(&key, &val, mc, &mask, &rec, &buf))
1.1       schwarze  483:                        break;
                    484:
1.5       kristaps  485:                /*
                    486:                 * See if this keyword record matches any of the
                    487:                 * expressions we have stored.
                    488:                 */
1.28      schwarze  489:                if ( ! exprmark(expr, buf, mask, NULL))
1.1       schwarze  490:                        continue;
                    491:
                    492:                /*
                    493:                 * O(log n) scan for prior records.  Since a record
                    494:                 * number is unbounded, this has decent performance over
                    495:                 * a complex hash function.
                    496:                 */
                    497:
                    498:                for (leaf = root; leaf >= 0; )
1.30      kristaps  499:                        if (rec > rs[leaf].rec &&
1.5       kristaps  500:                                        rs[leaf].rhs >= 0)
                    501:                                leaf = rs[leaf].rhs;
1.30      kristaps  502:                        else if (rec < rs[leaf].rec &&
1.5       kristaps  503:                                        rs[leaf].lhs >= 0)
                    504:                                leaf = rs[leaf].lhs;
1.12      schwarze  505:                        else
1.1       schwarze  506:                                break;
                    507:
1.5       kristaps  508:                /*
                    509:                 * If we find a record, see if it has already evaluated
                    510:                 * to true.  If it has, great, just keep going.  If not,
                    511:                 * try to evaluate it now and continue anyway.
                    512:                 */
                    513:
1.30      kristaps  514:                if (leaf >= 0 && rs[leaf].rec == rec) {
1.5       kristaps  515:                        if (0 == rs[leaf].matched)
1.28      schwarze  516:                                exprexec(expr, buf, mask, &rs[leaf]);
1.1       schwarze  517:                        continue;
1.5       kristaps  518:                }
1.1       schwarze  519:
                    520:                /*
1.5       kristaps  521:                 * We have a new file to examine.
                    522:                 * Extract the manpage's metadata from the index
                    523:                 * database, then begin partial evaluation.
1.1       schwarze  524:                 */
                    525:
1.28      schwarze  526:                key.data = &rec;
1.1       schwarze  527:                key.size = sizeof(recno_t);
                    528:
                    529:                if (0 != (*idx->get)(idx, &key, &val, 0))
                    530:                        break;
                    531:
1.5       kristaps  532:                r.lhs = r.rhs = -1;
1.11      kristaps  533:                if ( ! index_read(&key, &val, vol, mc, &r))
1.1       schwarze  534:                        break;
                    535:
1.5       kristaps  536:                /* XXX: this should be elsewhere, I guess? */
                    537:
1.30      kristaps  538:                if (opts->cat && strcasecmp(opts->cat, r.cat))
1.1       schwarze  539:                        continue;
1.22      kristaps  540:
1.30      kristaps  541:                if (opts->arch && *r.arch)
                    542:                        if (strcasecmp(opts->arch, r.arch))
1.22      kristaps  543:                                continue;
1.1       schwarze  544:
1.8       kristaps  545:                tree->node = rs = mandoc_realloc
1.30      kristaps  546:                        (rs, (tree->len + 1) * sizeof(struct res));
1.1       schwarze  547:
1.30      kristaps  548:                memcpy(&rs[tree->len], &r, sizeof(struct res));
                    549:                memset(&r, 0, sizeof(struct res));
1.12      schwarze  550:                rs[tree->len].matches =
1.8       kristaps  551:                        mandoc_calloc(terms, sizeof(int));
1.1       schwarze  552:
1.28      schwarze  553:                exprexec(expr, buf, mask, &rs[tree->len]);
1.12      schwarze  554:
1.1       schwarze  555:                /* Append to our tree. */
                    556:
                    557:                if (leaf >= 0) {
1.30      kristaps  558:                        if (rec > rs[leaf].rec)
1.8       kristaps  559:                                rs[leaf].rhs = tree->len;
1.1       schwarze  560:                        else
1.8       kristaps  561:                                rs[leaf].lhs = tree->len;
1.1       schwarze  562:                } else
1.8       kristaps  563:                        root = tree->len;
1.12      schwarze  564:
1.8       kristaps  565:                tree->len++;
1.1       schwarze  566:        }
1.12      schwarze  567:
1.8       kristaps  568:        (*btree->close)(btree);
                    569:        (*idx->close)(idx);
1.1       schwarze  570:
                    571:        free(buf);
1.30      kristaps  572:        RESFREE(&r);
1.8       kristaps  573:        return(1 == ch);
1.5       kristaps  574: }
                    575:
1.30      kristaps  576: void
                    577: resfree(struct res *rec, size_t sz)
1.5       kristaps  578: {
1.30      kristaps  579:        size_t           i;
1.5       kristaps  580:
1.30      kristaps  581:        for (i = 0; i < sz; i++)
                    582:                RESFREE(&rec[i]);
                    583:        free(rec);
1.1       schwarze  584: }
                    585:
1.13      kristaps  586: /*
                    587:  * Compile a list of straight-up terms.
                    588:  * The arguments are re-written into ~[[:<:]]term[[:>:]], or "term"
                    589:  * surrounded by word boundaries, then pumped through exprterm().
                    590:  * Terms are case-insensitive.
                    591:  * This emulates whatis(1) behaviour.
                    592:  */
                    593: struct expr *
                    594: termcomp(int argc, char *argv[], size_t *tt)
                    595: {
                    596:        char            *buf;
                    597:        int              pos;
                    598:        struct expr     *e, *next;
                    599:        size_t           sz;
                    600:
                    601:        buf = NULL;
                    602:        e = NULL;
                    603:        *tt = 0;
                    604:
1.15      schwarze  605:        for (pos = argc - 1; pos >= 0; pos--) {
                    606:                sz = strlen(argv[pos]) + 18;
1.13      kristaps  607:                buf = mandoc_realloc(buf, sz);
1.15      schwarze  608:                strlcpy(buf, "Nm~[[:<:]]", sz);
1.13      kristaps  609:                strlcat(buf, argv[pos], sz);
                    610:                strlcat(buf, "[[:>:]]", sz);
                    611:                if (NULL == (next = exprterm(buf, 0))) {
                    612:                        free(buf);
                    613:                        exprfree(e);
                    614:                        return(NULL);
                    615:                }
1.15      schwarze  616:                next->next = e;
1.13      kristaps  617:                e = next;
                    618:                (*tt)++;
                    619:        }
                    620:
                    621:        free(buf);
                    622:        return(e);
                    623: }
                    624:
                    625: /*
                    626:  * Compile a sequence of logical expressions.
                    627:  * See apropos.1 for a grammar of this sequence.
                    628:  */
1.1       schwarze  629: struct expr *
1.5       kristaps  630: exprcomp(int argc, char *argv[], size_t *tt)
1.1       schwarze  631: {
1.5       kristaps  632:        int              pos, lvl;
                    633:        struct expr     *e;
                    634:
                    635:        pos = lvl = 0;
                    636:        *tt = 0;
                    637:
                    638:        e = exprexpr(argc, argv, &pos, &lvl, tt);
                    639:
                    640:        if (0 == lvl && pos >= argc)
                    641:                return(e);
                    642:
                    643:        exprfree(e);
                    644:        return(NULL);
                    645: }
                    646:
                    647: /*
                    648:  * Compile an array of tokens into an expression.
                    649:  * An informal expression grammar is defined in apropos(1).
                    650:  * Return NULL if we fail doing so.  All memory will be cleaned up.
                    651:  * Return the root of the expression sequence if alright.
                    652:  */
                    653: static struct expr *
1.9       kristaps  654: exprexpr(int argc, char *argv[], int *pos, int *lvl, size_t *tt)
1.5       kristaps  655: {
                    656:        struct expr     *e, *first, *next;
                    657:        int              log;
                    658:
                    659:        first = next = NULL;
                    660:
                    661:        for ( ; *pos < argc; (*pos)++) {
                    662:                e = next;
                    663:
                    664:                /*
                    665:                 * Close out a subexpression.
                    666:                 */
                    667:
                    668:                if (NULL != e && 0 == strcmp(")", argv[*pos])) {
                    669:                        if (--(*lvl) < 0)
                    670:                                goto err;
                    671:                        break;
                    672:                }
                    673:
                    674:                /*
                    675:                 * Small note: if we're just starting, don't let "-a"
                    676:                 * and "-o" be considered logical operators: they're
                    677:                 * just tokens unless pairwise joining, in which case we
                    678:                 * record their existence (or assume "OR").
                    679:                 */
                    680:                log = 0;
                    681:
                    682:                if (NULL != e && 0 == strcmp("-a", argv[*pos]))
1.12      schwarze  683:                        log = 1;
1.5       kristaps  684:                else if (NULL != e && 0 == strcmp("-o", argv[*pos]))
                    685:                        log = 2;
                    686:
                    687:                if (log > 0 && ++(*pos) >= argc)
                    688:                        goto err;
                    689:
                    690:                /*
                    691:                 * Now we parse the term part.  This can begin with
                    692:                 * "-i", in which case the expression is case
                    693:                 * insensitive.
                    694:                 */
                    695:
                    696:                if (0 == strcmp("(", argv[*pos])) {
                    697:                        ++(*pos);
                    698:                        ++(*lvl);
                    699:                        next = mandoc_calloc(1, sizeof(struct expr));
                    700:                        next->subexpr = exprexpr(argc, argv, pos, lvl, tt);
                    701:                        if (NULL == next->subexpr) {
                    702:                                free(next);
                    703:                                next = NULL;
                    704:                        }
                    705:                } else if (0 == strcmp("-i", argv[*pos])) {
                    706:                        if (++(*pos) >= argc)
                    707:                                goto err;
                    708:                        next = exprterm(argv[*pos], 0);
                    709:                } else
                    710:                        next = exprterm(argv[*pos], 1);
                    711:
                    712:                if (NULL == next)
                    713:                        goto err;
                    714:
                    715:                next->and = log == 1;
                    716:                next->index = (int)(*tt)++;
                    717:
                    718:                /* Append to our chain of expressions. */
                    719:
                    720:                if (NULL == first) {
                    721:                        assert(NULL == e);
                    722:                        first = next;
                    723:                } else {
                    724:                        assert(NULL != e);
                    725:                        e->next = next;
                    726:                }
                    727:        }
                    728:
                    729:        return(first);
                    730: err:
                    731:        exprfree(first);
                    732:        return(NULL);
                    733: }
                    734:
                    735: /*
                    736:  * Parse a terminal expression with the grammar as defined in
                    737:  * apropos(1).
                    738:  * Return NULL if we fail the parse.
                    739:  */
                    740: static struct expr *
                    741: exprterm(char *buf, int cs)
                    742: {
                    743:        struct expr      e;
1.1       schwarze  744:        struct expr     *p;
1.3       schwarze  745:        char            *key;
1.5       kristaps  746:        int              i;
                    747:
                    748:        memset(&e, 0, sizeof(struct expr));
1.1       schwarze  749:
1.5       kristaps  750:        /* Choose regex or substring match. */
1.3       schwarze  751:
1.4       kristaps  752:        if (NULL == (e.v = strpbrk(buf, "=~"))) {
1.3       schwarze  753:                e.regex = 0;
1.4       kristaps  754:                e.v = buf;
1.3       schwarze  755:        } else {
                    756:                e.regex = '~' == *e.v;
                    757:                *e.v++ = '\0';
                    758:        }
1.1       schwarze  759:
1.5       kristaps  760:        /* Determine the record types to search for. */
1.3       schwarze  761:
                    762:        e.mask = 0;
1.4       kristaps  763:        if (buf < e.v) {
                    764:                while (NULL != (key = strsep(&buf, ","))) {
1.3       schwarze  765:                        i = 0;
                    766:                        while (types[i].mask &&
1.4       kristaps  767:                                        strcmp(types[i].name, key))
1.3       schwarze  768:                                i++;
                    769:                        e.mask |= types[i].mask;
                    770:                }
                    771:        }
                    772:        if (0 == e.mask)
                    773:                e.mask = TYPE_Nm | TYPE_Nd;
1.1       schwarze  774:
1.5       kristaps  775:        if (e.regex) {
1.13      kristaps  776:                i = REG_EXTENDED | REG_NOSUB | (cs ? 0 : REG_ICASE);
1.5       kristaps  777:                if (regcomp(&e.re, e.v, i))
                    778:                        return(NULL);
                    779:        }
1.1       schwarze  780:
1.3       schwarze  781:        e.v = mandoc_strdup(e.v);
1.1       schwarze  782:
                    783:        p = mandoc_calloc(1, sizeof(struct expr));
                    784:        memcpy(p, &e, sizeof(struct expr));
                    785:        return(p);
                    786: }
                    787:
                    788: void
                    789: exprfree(struct expr *p)
                    790: {
1.5       kristaps  791:        struct expr     *pp;
1.12      schwarze  792:
1.5       kristaps  793:        while (NULL != p) {
                    794:                if (p->subexpr)
                    795:                        exprfree(p->subexpr);
                    796:                if (p->regex)
                    797:                        regfree(&p->re);
                    798:                free(p->v);
                    799:                pp = p->next;
                    800:                free(p);
                    801:                p = pp;
                    802:        }
                    803: }
1.1       schwarze  804:
1.5       kristaps  805: static int
1.12      schwarze  806: exprmark(const struct expr *p, const char *cp,
1.6       kristaps  807:                uint64_t mask, int *ms)
1.5       kristaps  808: {
                    809:
                    810:        for ( ; p; p = p->next) {
                    811:                if (p->subexpr) {
                    812:                        if (exprmark(p->subexpr, cp, mask, ms))
                    813:                                return(1);
                    814:                        continue;
                    815:                } else if ( ! (mask & p->mask))
                    816:                        continue;
1.1       schwarze  817:
1.5       kristaps  818:                if (p->regex) {
                    819:                        if (regexec(&p->re, cp, 0, NULL, 0))
                    820:                                continue;
1.16      kristaps  821:                } else if (NULL == strcasestr(cp, p->v))
                    822:                        continue;
1.5       kristaps  823:
                    824:                if (NULL == ms)
                    825:                        return(1);
                    826:                else
                    827:                        ms[p->index] = 1;
                    828:        }
1.1       schwarze  829:
1.5       kristaps  830:        return(0);
1.1       schwarze  831: }
                    832:
                    833: static int
1.5       kristaps  834: expreval(const struct expr *p, int *ms)
1.1       schwarze  835: {
1.5       kristaps  836:        int              match;
1.1       schwarze  837:
1.5       kristaps  838:        /*
                    839:         * AND has precedence over OR.  Analysis is left-right, though
                    840:         * it doesn't matter because there are no side-effects.
                    841:         * Thus, step through pairwise ANDs and accumulate their Boolean
                    842:         * evaluation.  If we encounter a single true AND collection or
                    843:         * standalone term, the whole expression is true (by definition
                    844:         * of OR).
                    845:         */
                    846:
                    847:        for (match = 0; p && ! match; p = p->next) {
                    848:                /* Evaluate a subexpression, if applicable. */
                    849:                if (p->subexpr && ! ms[p->index])
                    850:                        ms[p->index] = expreval(p->subexpr, ms);
                    851:
                    852:                match = ms[p->index];
                    853:                for ( ; p->next && p->next->and; p = p->next) {
                    854:                        /* Evaluate a subexpression, if applicable. */
                    855:                        if (p->next->subexpr && ! ms[p->next->index])
1.12      schwarze  856:                                ms[p->next->index] =
1.5       kristaps  857:                                        expreval(p->next->subexpr, ms);
                    858:                        match = match && ms[p->next->index];
                    859:                }
                    860:        }
                    861:
                    862:        return(match);
                    863: }
                    864:
                    865: /*
                    866:  * First, update the array of terms for which this expression evaluates
                    867:  * to true.
                    868:  * Second, logically evaluate all terms over the updated array of truth
                    869:  * values.
                    870:  * If this evaluates to true, mark the expression as satisfied.
                    871:  */
                    872: static void
1.12      schwarze  873: exprexec(const struct expr *e, const char *cp,
1.30      kristaps  874:                uint64_t mask, struct res *r)
1.5       kristaps  875: {
1.1       schwarze  876:
1.5       kristaps  877:        assert(0 == r->matched);
1.12      schwarze  878:        exprmark(e, cp, mask, r->matches);
                    879:        r->matched = expreval(e, r->matches);
1.1       schwarze  880: }

CVSweb