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

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

CVSweb