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

Annotation of mandoc/apropos_db.c, Revision 1.20

1.20    ! kristaps    1: /*     $Id: apropos_db.c,v 1.19 2011/12/02 00:21:56 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));
1.20    ! kristaps  156:        info.lorder = 4321;
1.1       schwarze  157:        info.flags = R_DUP;
                    158:
1.2       schwarze  159:        db = dbopen(MANDOC_DB, O_RDONLY, 0, DB_BTREE, &info);
1.12      schwarze  160:        if (NULL != db)
1.1       schwarze  161:                return(db);
                    162:
                    163:        return(NULL);
                    164: }
                    165:
                    166: /*
                    167:  * Read a keyword from the database and normalise it.
                    168:  * Return 0 if the database is insane, else 1.
                    169:  */
                    170: static int
1.17      kristaps  171: btree_read(const DBT *k, const DBT *v,
                    172:                const struct mchars *mc,
                    173:                struct db_val *dbv, char **buf)
1.1       schwarze  174: {
1.17      kristaps  175:        const struct db_val *vp;
1.1       schwarze  176:
1.17      kristaps  177:        /* Are our sizes sane? */
                    178:        if (k->size < 2 || sizeof(struct db_val) != v->size)
                    179:                return(0);
1.6       kristaps  180:
1.17      kristaps  181:        /* Is our string nil-terminated? */
                    182:        if ('\0' != ((const char *)k->data)[(int)k->size - 1])
1.1       schwarze  183:                return(0);
                    184:
1.17      kristaps  185:        vp = v->data;
                    186:        norm_string((const char *)k->data, mc, buf);
1.18      kristaps  187:        dbv->rec = betoh32(vp->rec);
                    188:        dbv->mask = betoh64(vp->mask);
1.1       schwarze  189:        return(1);
                    190: }
                    191:
                    192: /*
                    193:  * Take a Unicode codepoint and produce its UTF-8 encoding.
                    194:  * This isn't the best way to do this, but it works.
1.12      schwarze  195:  * The magic numbers are from the UTF-8 packaging.
1.1       schwarze  196:  * They're not as scary as they seem: read the UTF-8 spec for details.
                    197:  */
                    198: static size_t
                    199: norm_utf8(unsigned int cp, char out[7])
                    200: {
                    201:        size_t           rc;
                    202:
                    203:        rc = 0;
                    204:
                    205:        if (cp <= 0x0000007F) {
                    206:                rc = 1;
                    207:                out[0] = (char)cp;
                    208:        } else if (cp <= 0x000007FF) {
                    209:                rc = 2;
                    210:                out[0] = (cp >> 6  & 31) | 192;
                    211:                out[1] = (cp       & 63) | 128;
                    212:        } else if (cp <= 0x0000FFFF) {
                    213:                rc = 3;
                    214:                out[0] = (cp >> 12 & 15) | 224;
                    215:                out[1] = (cp >> 6  & 63) | 128;
                    216:                out[2] = (cp       & 63) | 128;
                    217:        } else if (cp <= 0x001FFFFF) {
                    218:                rc = 4;
                    219:                out[0] = (cp >> 18 & 7) | 240;
                    220:                out[1] = (cp >> 12 & 63) | 128;
                    221:                out[2] = (cp >> 6  & 63) | 128;
                    222:                out[3] = (cp       & 63) | 128;
                    223:        } else if (cp <= 0x03FFFFFF) {
                    224:                rc = 5;
                    225:                out[0] = (cp >> 24 & 3) | 248;
                    226:                out[1] = (cp >> 18 & 63) | 128;
                    227:                out[2] = (cp >> 12 & 63) | 128;
                    228:                out[3] = (cp >> 6  & 63) | 128;
                    229:                out[4] = (cp       & 63) | 128;
                    230:        } else if (cp <= 0x7FFFFFFF) {
                    231:                rc = 6;
                    232:                out[0] = (cp >> 30 & 1) | 252;
                    233:                out[1] = (cp >> 24 & 63) | 128;
                    234:                out[2] = (cp >> 18 & 63) | 128;
                    235:                out[3] = (cp >> 12 & 63) | 128;
                    236:                out[4] = (cp >> 6  & 63) | 128;
                    237:                out[5] = (cp       & 63) | 128;
                    238:        } else
                    239:                return(0);
                    240:
                    241:        out[rc] = '\0';
                    242:        return(rc);
                    243: }
                    244:
                    245: /*
                    246:  * Normalise strings from the index and database.
                    247:  * These strings are escaped as defined by mandoc_char(7) along with
                    248:  * other goop in mandoc.h (e.g., soft hyphens).
                    249:  * This function normalises these into a nice UTF-8 string.
                    250:  * Returns 0 if the database is fucked.
                    251:  */
                    252: static void
                    253: norm_string(const char *val, const struct mchars *mc, char **buf)
                    254: {
                    255:        size_t            sz, bsz;
                    256:        char              utfbuf[7];
                    257:        const char       *seq, *cpp;
                    258:        int               len, u, pos;
                    259:        enum mandoc_esc   esc;
1.12      schwarze  260:        static const char res[] = { '\\', '\t',
1.1       schwarze  261:                                ASCII_NBRSP, ASCII_HYPH, '\0' };
                    262:
                    263:        /* Pre-allocate by the length of the input */
                    264:
                    265:        bsz = strlen(val) + 1;
                    266:        *buf = mandoc_realloc(*buf, bsz);
                    267:        pos = 0;
                    268:
                    269:        while ('\0' != *val) {
                    270:                /*
                    271:                 * Halt on the first escape sequence.
                    272:                 * This also halts on the end of string, in which case
                    273:                 * we just copy, fallthrough, and exit the loop.
                    274:                 */
                    275:                if ((sz = strcspn(val, res)) > 0) {
                    276:                        memcpy(&(*buf)[pos], val, sz);
                    277:                        pos += (int)sz;
                    278:                        val += (int)sz;
                    279:                }
                    280:
                    281:                if (ASCII_HYPH == *val) {
                    282:                        (*buf)[pos++] = '-';
                    283:                        val++;
                    284:                        continue;
                    285:                } else if ('\t' == *val || ASCII_NBRSP == *val) {
                    286:                        (*buf)[pos++] = ' ';
                    287:                        val++;
                    288:                        continue;
                    289:                } else if ('\\' != *val)
                    290:                        break;
                    291:
                    292:                /* Read past the slash. */
                    293:
                    294:                val++;
                    295:                u = 0;
                    296:
                    297:                /*
                    298:                 * Parse the escape sequence and see if it's a
                    299:                 * predefined character or special character.
                    300:                 */
                    301:
                    302:                esc = mandoc_escape(&val, &seq, &len);
                    303:                if (ESCAPE_ERROR == esc)
                    304:                        break;
                    305:
1.12      schwarze  306:                /*
1.1       schwarze  307:                 * XXX - this just does UTF-8, but we need to know
                    308:                 * beforehand whether we should do text substitution.
                    309:                 */
                    310:
                    311:                switch (esc) {
                    312:                case (ESCAPE_SPECIAL):
                    313:                        if (0 != (u = mchars_spec2cp(mc, seq, len)))
                    314:                                break;
                    315:                        /* FALLTHROUGH */
                    316:                default:
                    317:                        continue;
                    318:                }
                    319:
                    320:                /*
                    321:                 * If we have a Unicode codepoint, try to convert that
                    322:                 * to a UTF-8 byte string.
                    323:                 */
                    324:
                    325:                cpp = utfbuf;
                    326:                if (0 == (sz = norm_utf8(u, utfbuf)))
                    327:                        continue;
                    328:
                    329:                /* Copy the rendered glyph into the stream. */
                    330:
                    331:                sz = strlen(cpp);
                    332:                bsz += sz;
                    333:
                    334:                *buf = mandoc_realloc(*buf, bsz);
                    335:
                    336:                memcpy(&(*buf)[pos], cpp, sz);
                    337:                pos += (int)sz;
                    338:        }
                    339:
                    340:        (*buf)[pos] = '\0';
                    341: }
                    342:
                    343: /*
                    344:  * Open the filename-index mandoc-db database.
                    345:  * Returns NULL if opening failed.
                    346:  */
                    347: static DB *
                    348: index_open(void)
                    349: {
                    350:        DB              *db;
                    351:
1.2       schwarze  352:        db = dbopen(MANDOC_IDX, O_RDONLY, 0, DB_RECNO, NULL);
1.1       schwarze  353:        if (NULL != db)
                    354:                return(db);
                    355:
                    356:        return(NULL);
                    357: }
                    358:
                    359: /*
                    360:  * Safely unpack from an index file record into the structure.
                    361:  * Returns 1 if an entry was unpacked, 0 if the database is insane.
                    362:  */
                    363: static int
1.11      kristaps  364: index_read(const DBT *key, const DBT *val, int index,
1.1       schwarze  365:                const struct mchars *mc, struct rec *rec)
                    366: {
                    367:        size_t           left;
                    368:        char            *np, *cp;
                    369:
                    370: #define        INDEX_BREAD(_dst) \
                    371:        do { \
                    372:                if (NULL == (np = memchr(cp, '\0', left))) \
                    373:                        return(0); \
                    374:                norm_string(cp, mc, &(_dst)); \
                    375:                left -= (np - cp) + 1; \
                    376:                cp = np + 1; \
                    377:        } while (/* CONSTCOND */ 0)
                    378:
                    379:        left = val->size;
                    380:        cp = (char *)val->data;
                    381:
1.5       kristaps  382:        rec->res.rec = *(recno_t *)key->data;
1.11      kristaps  383:        rec->res.volume = index;
1.1       schwarze  384:
1.14      schwarze  385:        INDEX_BREAD(rec->res.type);
1.5       kristaps  386:        INDEX_BREAD(rec->res.file);
                    387:        INDEX_BREAD(rec->res.cat);
                    388:        INDEX_BREAD(rec->res.title);
                    389:        INDEX_BREAD(rec->res.arch);
                    390:        INDEX_BREAD(rec->res.desc);
1.1       schwarze  391:        return(1);
                    392: }
                    393:
                    394: /*
1.10      kristaps  395:  * Search mandocdb databases in paths for expression "expr".
1.1       schwarze  396:  * Filter out by "opts".
                    397:  * Call "res" with the results, which may be zero.
1.5       kristaps  398:  * Return 0 if there was a database error, else return 1.
1.1       schwarze  399:  */
1.5       kristaps  400: int
1.10      kristaps  401: apropos_search(int pathsz, char **paths, const struct opts *opts,
1.12      schwarze  402:                const struct expr *expr, size_t terms, void *arg,
1.5       kristaps  403:                void (*res)(struct res *, size_t, void *))
1.1       schwarze  404: {
1.8       kristaps  405:        struct rectree   tree;
                    406:        struct mchars   *mc;
                    407:        struct res      *ress;
                    408:        int              i, mlen, rc;
                    409:
                    410:        memset(&tree, 0, sizeof(struct rectree));
                    411:
1.10      kristaps  412:        rc = 0;
1.8       kristaps  413:        mc = mchars_alloc();
                    414:
1.10      kristaps  415:        /*
                    416:         * Main loop.  Change into the directory containing manpage
                    417:         * databases.  Run our expession over each database in the set.
                    418:         */
                    419:
                    420:        for (i = 0; i < pathsz; i++) {
                    421:                if (chdir(paths[i]))
1.8       kristaps  422:                        continue;
1.11      kristaps  423:                if ( ! single_search(&tree, opts, expr, terms, mc, i))
1.10      kristaps  424:                        goto out;
1.8       kristaps  425:        }
                    426:
                    427:        /*
1.10      kristaps  428:         * Count matching files, transfer to a "clean" array, then feed
                    429:         * them to the output handler.
1.8       kristaps  430:         */
                    431:
                    432:        for (mlen = i = 0; i < tree.len; i++)
                    433:                if (tree.node[i].matched)
                    434:                        mlen++;
                    435:
                    436:        ress = mandoc_malloc(mlen * sizeof(struct res));
                    437:
                    438:        for (mlen = i = 0; i < tree.len; i++)
                    439:                if (tree.node[i].matched)
1.12      schwarze  440:                        memcpy(&ress[mlen++], &tree.node[i].res,
1.8       kristaps  441:                                        sizeof(struct res));
                    442:
                    443:        (*res)(ress, mlen, arg);
                    444:        free(ress);
                    445:
1.10      kristaps  446:        rc = 1;
                    447: out:
1.8       kristaps  448:        for (i = 0; i < tree.len; i++)
                    449:                recfree(&tree.node[i]);
                    450:
                    451:        free(tree.node);
                    452:        mchars_free(mc);
                    453:        return(rc);
                    454: }
                    455:
                    456: static int
                    457: single_search(struct rectree *tree, const struct opts *opts,
                    458:                const struct expr *expr, size_t terms,
1.11      kristaps  459:                struct mchars *mc, int vol)
1.8       kristaps  460: {
                    461:        int              root, leaf, ch;
1.1       schwarze  462:        DBT              key, val;
                    463:        DB              *btree, *idx;
                    464:        char            *buf;
1.5       kristaps  465:        struct rec      *rs;
                    466:        struct rec       r;
1.17      kristaps  467:        struct db_val    vb;
1.1       schwarze  468:
                    469:        root    = -1;
                    470:        leaf    = -1;
                    471:        btree   = NULL;
                    472:        idx     = NULL;
                    473:        buf     = NULL;
1.8       kristaps  474:        rs      = tree->node;
1.1       schwarze  475:
1.5       kristaps  476:        memset(&r, 0, sizeof(struct rec));
1.1       schwarze  477:
1.12      schwarze  478:        if (NULL == (btree = btree_open()))
1.10      kristaps  479:                return(1);
1.1       schwarze  480:
1.8       kristaps  481:        if (NULL == (idx = index_open())) {
                    482:                (*btree->close)(btree);
1.10      kristaps  483:                return(1);
1.8       kristaps  484:        }
1.1       schwarze  485:
                    486:        while (0 == (ch = (*btree->seq)(btree, &key, &val, R_NEXT))) {
1.17      kristaps  487:                if ( ! btree_read(&key, &val, mc, &vb, &buf))
1.1       schwarze  488:                        break;
                    489:
1.5       kristaps  490:                /*
                    491:                 * See if this keyword record matches any of the
                    492:                 * expressions we have stored.
                    493:                 */
1.17      kristaps  494:                if ( ! exprmark(expr, buf, vb.mask, NULL))
1.1       schwarze  495:                        continue;
                    496:
                    497:                /*
                    498:                 * O(log n) scan for prior records.  Since a record
                    499:                 * number is unbounded, this has decent performance over
                    500:                 * a complex hash function.
                    501:                 */
                    502:
                    503:                for (leaf = root; leaf >= 0; )
1.17      kristaps  504:                        if (vb.rec > rs[leaf].res.rec &&
1.5       kristaps  505:                                        rs[leaf].rhs >= 0)
                    506:                                leaf = rs[leaf].rhs;
1.17      kristaps  507:                        else if (vb.rec < rs[leaf].res.rec &&
1.5       kristaps  508:                                        rs[leaf].lhs >= 0)
                    509:                                leaf = rs[leaf].lhs;
1.12      schwarze  510:                        else
1.1       schwarze  511:                                break;
                    512:
1.5       kristaps  513:                /*
                    514:                 * If we find a record, see if it has already evaluated
                    515:                 * to true.  If it has, great, just keep going.  If not,
                    516:                 * try to evaluate it now and continue anyway.
                    517:                 */
                    518:
1.17      kristaps  519:                if (leaf >= 0 && rs[leaf].res.rec == vb.rec) {
1.5       kristaps  520:                        if (0 == rs[leaf].matched)
1.17      kristaps  521:                                exprexec(expr, buf, vb.mask, &rs[leaf]);
1.1       schwarze  522:                        continue;
1.5       kristaps  523:                }
1.1       schwarze  524:
                    525:                /*
1.5       kristaps  526:                 * We have a new file to examine.
                    527:                 * Extract the manpage's metadata from the index
                    528:                 * database, then begin partial evaluation.
1.1       schwarze  529:                 */
                    530:
1.17      kristaps  531:                key.data = &vb.rec;
1.1       schwarze  532:                key.size = sizeof(recno_t);
                    533:
                    534:                if (0 != (*idx->get)(idx, &key, &val, 0))
                    535:                        break;
                    536:
1.5       kristaps  537:                r.lhs = r.rhs = -1;
1.11      kristaps  538:                if ( ! index_read(&key, &val, vol, mc, &r))
1.1       schwarze  539:                        break;
                    540:
1.5       kristaps  541:                /* XXX: this should be elsewhere, I guess? */
                    542:
                    543:                if (opts->cat && strcasecmp(opts->cat, r.res.cat))
1.1       schwarze  544:                        continue;
1.5       kristaps  545:                if (opts->arch && strcasecmp(opts->arch, r.res.arch))
1.1       schwarze  546:                        continue;
                    547:
1.8       kristaps  548:                tree->node = rs = mandoc_realloc
                    549:                        (rs, (tree->len + 1) * sizeof(struct rec));
1.1       schwarze  550:
1.8       kristaps  551:                memcpy(&rs[tree->len], &r, sizeof(struct rec));
1.12      schwarze  552:                rs[tree->len].matches =
1.8       kristaps  553:                        mandoc_calloc(terms, sizeof(int));
1.1       schwarze  554:
1.17      kristaps  555:                exprexec(expr, buf, vb.mask, &rs[tree->len]);
1.12      schwarze  556:
1.1       schwarze  557:                /* Append to our tree. */
                    558:
                    559:                if (leaf >= 0) {
1.17      kristaps  560:                        if (vb.rec > rs[leaf].res.rec)
1.8       kristaps  561:                                rs[leaf].rhs = tree->len;
1.1       schwarze  562:                        else
1.8       kristaps  563:                                rs[leaf].lhs = tree->len;
1.1       schwarze  564:                } else
1.8       kristaps  565:                        root = tree->len;
1.12      schwarze  566:
1.5       kristaps  567:                memset(&r, 0, sizeof(struct rec));
1.8       kristaps  568:                tree->len++;
1.1       schwarze  569:        }
1.12      schwarze  570:
1.8       kristaps  571:        (*btree->close)(btree);
                    572:        (*idx->close)(idx);
1.1       schwarze  573:
                    574:        free(buf);
1.8       kristaps  575:        return(1 == ch);
1.5       kristaps  576: }
                    577:
                    578: static void
                    579: recfree(struct rec *rec)
                    580: {
                    581:
1.17      kristaps  582:        free(rec->res.type);
1.5       kristaps  583:        free(rec->res.file);
                    584:        free(rec->res.cat);
                    585:        free(rec->res.title);
                    586:        free(rec->res.arch);
                    587:        free(rec->res.desc);
                    588:
                    589:        free(rec->matches);
1.1       schwarze  590: }
                    591:
1.13      kristaps  592: /*
                    593:  * Compile a list of straight-up terms.
                    594:  * The arguments are re-written into ~[[:<:]]term[[:>:]], or "term"
                    595:  * surrounded by word boundaries, then pumped through exprterm().
                    596:  * Terms are case-insensitive.
                    597:  * This emulates whatis(1) behaviour.
                    598:  */
                    599: struct expr *
                    600: termcomp(int argc, char *argv[], size_t *tt)
                    601: {
                    602:        char            *buf;
                    603:        int              pos;
                    604:        struct expr     *e, *next;
                    605:        size_t           sz;
                    606:
                    607:        buf = NULL;
                    608:        e = NULL;
                    609:        *tt = 0;
                    610:
1.15      schwarze  611:        for (pos = argc - 1; pos >= 0; pos--) {
                    612:                sz = strlen(argv[pos]) + 18;
1.13      kristaps  613:                buf = mandoc_realloc(buf, sz);
1.15      schwarze  614:                strlcpy(buf, "Nm~[[:<:]]", sz);
1.13      kristaps  615:                strlcat(buf, argv[pos], sz);
                    616:                strlcat(buf, "[[:>:]]", sz);
                    617:                if (NULL == (next = exprterm(buf, 0))) {
                    618:                        free(buf);
                    619:                        exprfree(e);
                    620:                        return(NULL);
                    621:                }
1.15      schwarze  622:                next->next = e;
1.13      kristaps  623:                e = next;
                    624:                (*tt)++;
                    625:        }
                    626:
                    627:        free(buf);
                    628:        return(e);
                    629: }
                    630:
                    631: /*
                    632:  * Compile a sequence of logical expressions.
                    633:  * See apropos.1 for a grammar of this sequence.
                    634:  */
1.1       schwarze  635: struct expr *
1.5       kristaps  636: exprcomp(int argc, char *argv[], size_t *tt)
1.1       schwarze  637: {
1.5       kristaps  638:        int              pos, lvl;
                    639:        struct expr     *e;
                    640:
                    641:        pos = lvl = 0;
                    642:        *tt = 0;
                    643:
                    644:        e = exprexpr(argc, argv, &pos, &lvl, tt);
                    645:
                    646:        if (0 == lvl && pos >= argc)
                    647:                return(e);
                    648:
                    649:        exprfree(e);
                    650:        return(NULL);
                    651: }
                    652:
                    653: /*
                    654:  * Compile an array of tokens into an expression.
                    655:  * An informal expression grammar is defined in apropos(1).
                    656:  * Return NULL if we fail doing so.  All memory will be cleaned up.
                    657:  * Return the root of the expression sequence if alright.
                    658:  */
                    659: static struct expr *
1.9       kristaps  660: exprexpr(int argc, char *argv[], int *pos, int *lvl, size_t *tt)
1.5       kristaps  661: {
                    662:        struct expr     *e, *first, *next;
                    663:        int              log;
                    664:
                    665:        first = next = NULL;
                    666:
                    667:        for ( ; *pos < argc; (*pos)++) {
                    668:                e = next;
                    669:
                    670:                /*
                    671:                 * Close out a subexpression.
                    672:                 */
                    673:
                    674:                if (NULL != e && 0 == strcmp(")", argv[*pos])) {
                    675:                        if (--(*lvl) < 0)
                    676:                                goto err;
                    677:                        break;
                    678:                }
                    679:
                    680:                /*
                    681:                 * Small note: if we're just starting, don't let "-a"
                    682:                 * and "-o" be considered logical operators: they're
                    683:                 * just tokens unless pairwise joining, in which case we
                    684:                 * record their existence (or assume "OR").
                    685:                 */
                    686:                log = 0;
                    687:
                    688:                if (NULL != e && 0 == strcmp("-a", argv[*pos]))
1.12      schwarze  689:                        log = 1;
1.5       kristaps  690:                else if (NULL != e && 0 == strcmp("-o", argv[*pos]))
                    691:                        log = 2;
                    692:
                    693:                if (log > 0 && ++(*pos) >= argc)
                    694:                        goto err;
                    695:
                    696:                /*
                    697:                 * Now we parse the term part.  This can begin with
                    698:                 * "-i", in which case the expression is case
                    699:                 * insensitive.
                    700:                 */
                    701:
                    702:                if (0 == strcmp("(", argv[*pos])) {
                    703:                        ++(*pos);
                    704:                        ++(*lvl);
                    705:                        next = mandoc_calloc(1, sizeof(struct expr));
                    706:                        next->subexpr = exprexpr(argc, argv, pos, lvl, tt);
                    707:                        if (NULL == next->subexpr) {
                    708:                                free(next);
                    709:                                next = NULL;
                    710:                        }
                    711:                } else if (0 == strcmp("-i", argv[*pos])) {
                    712:                        if (++(*pos) >= argc)
                    713:                                goto err;
                    714:                        next = exprterm(argv[*pos], 0);
                    715:                } else
                    716:                        next = exprterm(argv[*pos], 1);
                    717:
                    718:                if (NULL == next)
                    719:                        goto err;
                    720:
                    721:                next->and = log == 1;
                    722:                next->index = (int)(*tt)++;
                    723:
                    724:                /* Append to our chain of expressions. */
                    725:
                    726:                if (NULL == first) {
                    727:                        assert(NULL == e);
                    728:                        first = next;
                    729:                } else {
                    730:                        assert(NULL != e);
                    731:                        e->next = next;
                    732:                }
                    733:        }
                    734:
                    735:        return(first);
                    736: err:
                    737:        exprfree(first);
                    738:        return(NULL);
                    739: }
                    740:
                    741: /*
                    742:  * Parse a terminal expression with the grammar as defined in
                    743:  * apropos(1).
                    744:  * Return NULL if we fail the parse.
                    745:  */
                    746: static struct expr *
                    747: exprterm(char *buf, int cs)
                    748: {
                    749:        struct expr      e;
1.1       schwarze  750:        struct expr     *p;
1.3       schwarze  751:        char            *key;
1.5       kristaps  752:        int              i;
                    753:
                    754:        memset(&e, 0, sizeof(struct expr));
1.1       schwarze  755:
1.5       kristaps  756:        /* Choose regex or substring match. */
1.3       schwarze  757:
1.4       kristaps  758:        if (NULL == (e.v = strpbrk(buf, "=~"))) {
1.3       schwarze  759:                e.regex = 0;
1.4       kristaps  760:                e.v = buf;
1.3       schwarze  761:        } else {
                    762:                e.regex = '~' == *e.v;
                    763:                *e.v++ = '\0';
                    764:        }
1.1       schwarze  765:
1.5       kristaps  766:        /* Determine the record types to search for. */
1.3       schwarze  767:
                    768:        e.mask = 0;
1.4       kristaps  769:        if (buf < e.v) {
                    770:                while (NULL != (key = strsep(&buf, ","))) {
1.3       schwarze  771:                        i = 0;
                    772:                        while (types[i].mask &&
1.4       kristaps  773:                                        strcmp(types[i].name, key))
1.3       schwarze  774:                                i++;
                    775:                        e.mask |= types[i].mask;
                    776:                }
                    777:        }
                    778:        if (0 == e.mask)
                    779:                e.mask = TYPE_Nm | TYPE_Nd;
1.1       schwarze  780:
1.5       kristaps  781:        if (e.regex) {
1.13      kristaps  782:                i = REG_EXTENDED | REG_NOSUB | (cs ? 0 : REG_ICASE);
1.5       kristaps  783:                if (regcomp(&e.re, e.v, i))
                    784:                        return(NULL);
                    785:        }
1.1       schwarze  786:
1.3       schwarze  787:        e.v = mandoc_strdup(e.v);
1.1       schwarze  788:
                    789:        p = mandoc_calloc(1, sizeof(struct expr));
                    790:        memcpy(p, &e, sizeof(struct expr));
                    791:        return(p);
                    792: }
                    793:
                    794: void
                    795: exprfree(struct expr *p)
                    796: {
1.5       kristaps  797:        struct expr     *pp;
1.12      schwarze  798:
1.5       kristaps  799:        while (NULL != p) {
                    800:                if (p->subexpr)
                    801:                        exprfree(p->subexpr);
                    802:                if (p->regex)
                    803:                        regfree(&p->re);
                    804:                free(p->v);
                    805:                pp = p->next;
                    806:                free(p);
                    807:                p = pp;
                    808:        }
                    809: }
1.1       schwarze  810:
1.5       kristaps  811: static int
1.12      schwarze  812: exprmark(const struct expr *p, const char *cp,
1.6       kristaps  813:                uint64_t mask, int *ms)
1.5       kristaps  814: {
                    815:
                    816:        for ( ; p; p = p->next) {
                    817:                if (p->subexpr) {
                    818:                        if (exprmark(p->subexpr, cp, mask, ms))
                    819:                                return(1);
                    820:                        continue;
                    821:                } else if ( ! (mask & p->mask))
                    822:                        continue;
1.1       schwarze  823:
1.5       kristaps  824:                if (p->regex) {
                    825:                        if (regexec(&p->re, cp, 0, NULL, 0))
                    826:                                continue;
1.16      kristaps  827:                } else if (NULL == strcasestr(cp, p->v))
                    828:                        continue;
1.5       kristaps  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