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

Annotation of mandoc/apropos_db.c, Revision 1.14

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

CVSweb