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

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

CVSweb