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

Annotation of mandoc/apropos_db.c, Revision 1.17

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

CVSweb