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

Annotation of mandoc/apropos_db.c, Revision 1.19

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

CVSweb