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

Annotation of mandoc/mandocdb.c, Revision 1.50

1.50    ! kristaps    1: /*     $Id: mandocdb.c,v 1.49 2012/05/27 17:48:57 schwarze Exp $ */
1.1       kristaps    2: /*
1.48      schwarze    3:  * Copyright (c) 2011, 2012 Kristaps Dzonsons <kristaps@bsd.lv>
                      4:  * Copyright (c) 2011, 2012 Ingo Schwarze <schwarze@openbsd.org>
1.1       kristaps    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: #ifdef HAVE_CONFIG_H
                     19: #include "config.h"
                     20: #endif
                     21:
                     22: #include <sys/param.h>
1.50    ! kristaps   23: #include <sys/stat.h>
1.1       kristaps   24:
                     25: #include <assert.h>
1.43      kristaps   26: #include <ctype.h>
1.45      kristaps   27: #include <errno.h>
1.1       kristaps   28: #include <fcntl.h>
1.50    ! kristaps   29: #include <fts.h>
1.1       kristaps   30: #include <getopt.h>
1.50    ! kristaps   31: #include <stddef.h>
1.1       kristaps   32: #include <stdint.h>
                     33: #include <stdlib.h>
                     34: #include <string.h>
1.17      schwarze   35: #include <unistd.h>
1.1       kristaps   36:
1.50    ! kristaps   37: #include <ohash.h>
        !            38: #include <sqlite3.h>
1.1       kristaps   39:
1.50    ! kristaps   40: #include "mdoc.h"
1.1       kristaps   41: #include "man.h"
                     42: #include "mandoc.h"
1.8       schwarze   43: #include "mandocdb.h"
1.10      kristaps   44: #include "manpath.h"
1.1       kristaps   45:
1.50    ! kristaps   46: /* Post a warning to stderr. */
1.45      kristaps   47: #define WARNING(_f, _b, _fmt, _args...) \
                     48:        do if (warnings) { \
                     49:                fprintf(stderr, "%s: ", (_b)); \
                     50:                fprintf(stderr, (_fmt), ##_args); \
                     51:                if ('\0' != *(_f)) \
                     52:                        fprintf(stderr, ": %s", (_f)); \
                     53:                fprintf(stderr, "\n"); \
                     54:        } while (/* CONSTCOND */ 0)
1.50    ! kristaps   55: /* Post a "verbose" message to stderr. */
        !            56: #define        DEBUG(_f, _b, _fmt, _args...) \
        !            57:        do if (verb) { \
        !            58:                fprintf(stderr, "%s: ", (_b)); \
        !            59:                fprintf(stderr, (_fmt), ##_args); \
        !            60:                fprintf(stderr, ": %s\n", (_f)); \
        !            61:        } while (/* CONSTCOND */ 0)
1.38      schwarze   62:
1.50    ! kristaps   63: enum   op {
        !            64:        OP_DEFAULT = 0, /* new dbs from dir list or default config */
        !            65:        OP_CONFFILE, /* new databases from custom config file */
        !            66:        OP_UPDATE, /* delete/add entries in existing database */
        !            67:        OP_DELETE, /* delete entries from existing database */
        !            68:        OP_TEST /* change no databases, report potential problems */
1.38      schwarze   69: };
                     70:
1.50    ! kristaps   71: enum   form {
        !            72:        FORM_SRC, /* format is -man or -mdoc */
        !            73:        FORM_CAT, /* format is cat */
        !            74:        FORM_NONE /* format is unknown */
        !            75: };
1.38      schwarze   76:
1.50    ! kristaps   77: struct str {
        !            78:        char            *utf8; /* key in UTF-8 form */
        !            79:        const struct of *of; /* if set, the owning parse */
        !            80:        struct str      *next; /* next in owning parse sequence */
        !            81:        uint64_t         mask; /* bitmask in sequence */
        !            82:        char             key[1]; /* the string itself */
1.38      schwarze   83: };
                     84:
1.50    ! kristaps   85: struct id {
        !            86:        ino_t            ino;
        !            87:        dev_t            dev;
        !            88: };
1.5       kristaps   89:
1.3       kristaps   90: struct of {
1.50    ! kristaps   91:        struct id        id; /* used for hashing routine */
        !            92:        struct of       *next; /* next in ofs */
        !            93:        enum form        dform; /* path-cued form */
        !            94:        enum form        sform; /* suffix-cued form */
        !            95:        char             file[MAXPATHLEN]; /* filename rel. to manpath */
        !            96:        const char      *desc; /* parsed description */
        !            97:        const char      *sec; /* suffix-cued section (or empty) */
        !            98:        const char      *dsec; /* path-cued section (or empty) */
        !            99:        const char      *arch; /* path-cued arch. (or empty) */
        !           100:        const char      *name; /* name (from filename) (not empty) */
1.3       kristaps  101: };
                    102:
1.50    ! kristaps  103: enum   stmt {
        !           104:        STMT_DELETE = 0, /* delete manpage */
        !           105:        STMT_INSERT_DOC, /* insert manpage */
        !           106:        STMT_INSERT_KEY, /* insert parsed key */
        !           107:        STMT__MAX
1.1       kristaps  108: };
                    109:
1.50    ! kristaps  110: typedef        int (*mdoc_fp)(struct of *, const struct mdoc_node *);
1.1       kristaps  111:
1.50    ! kristaps  112: struct mdoc_handler {
        !           113:        mdoc_fp          fp; /* optional handler */
        !           114:        uint64_t         mask;  /* set unless handler returns 0 */
        !           115:        int              flags;  /* for use by pmdoc_node */
        !           116: #define        MDOCF_CHILD      0x01  /* automatically index child nodes */
1.1       kristaps  117: };
                    118:
1.50    ! kristaps  119: static void     dbclose(const char *, int);
        !           120: static void     dbindex(struct mchars *, int,
        !           121:                        const struct of *, const char *);
        !           122: static int      dbopen(const char *, int);
        !           123: static void     dbprune(const char *);
        !           124: static void     fileadd(struct of *);
        !           125: static int      filecheck(const char *);
        !           126: static void     filescan(const char *, const char *);
        !           127: static struct str *hashget(const char *, size_t);
        !           128: static void    *hash_alloc(size_t, void *);
        !           129: static void     hash_free(void *, size_t, void *);
        !           130: static void    *hash_halloc(size_t, void *);
        !           131: static void     inoadd(const struct stat *, struct of *);
        !           132: static int      inocheck(const struct stat *);
        !           133: static void     ofadd(const char *, int, const char *,
        !           134:                        const char *, const char *, const char *,
        !           135:                        const char *, const struct stat *);
        !           136: static void     offree(void);
        !           137: static int      ofmerge(struct mchars *, struct mparse *, const char *);
        !           138: static void     parse_catpage(struct of *, const char *);
        !           139: static int      parse_man(struct of *,
        !           140:                        const struct man_node *);
        !           141: static void     parse_mdoc(struct of *, const struct mdoc_node *);
        !           142: static int      parse_mdoc_body(struct of *, const struct mdoc_node *);
        !           143: static int      parse_mdoc_head(struct of *, const struct mdoc_node *);
        !           144: static int      parse_mdoc_Fd(struct of *, const struct mdoc_node *);
        !           145: static int      parse_mdoc_Fn(struct of *, const struct mdoc_node *);
        !           146: static int      parse_mdoc_In(struct of *, const struct mdoc_node *);
        !           147: static int      parse_mdoc_Nd(struct of *, const struct mdoc_node *);
        !           148: static int      parse_mdoc_Nm(struct of *, const struct mdoc_node *);
        !           149: static int      parse_mdoc_Sh(struct of *, const struct mdoc_node *);
        !           150: static int      parse_mdoc_St(struct of *, const struct mdoc_node *);
        !           151: static int      parse_mdoc_Xr(struct of *, const struct mdoc_node *);
        !           152: static int      path_reset(const char *, int, const char *);
        !           153: static void     putkey(const struct of *,
        !           154:                        const char *, uint64_t);
        !           155: static void     putkeys(const struct of *,
        !           156:                        const char *, int, uint64_t);
        !           157: static void     putmdockey(const struct of *,
        !           158:                        const struct mdoc_node *, uint64_t);
        !           159: static char    *stradd(const char *);
        !           160: static char    *straddbuf(const char *, size_t);
        !           161: static int      treescan(const char *);
        !           162: static size_t   utf8(unsigned int, char [7]);
        !           163: static void     utf8key(struct mchars *, struct str *);
        !           164: static void     wordaddbuf(const struct of *,
        !           165:                        const char *, size_t, uint64_t);
        !           166:
        !           167: static char            *progname;
        !           168: static int              use_all; /* use all found files */
        !           169: static int              nodb; /* no database changes */
        !           170: static int              verb; /* print what we're doing */
        !           171: static int              warnings; /* warn about crap */
        !           172: static enum op          op; /* operational mode */
        !           173: static struct ohash     inos; /* table of inodes/devices */
        !           174: static struct ohash     filenames; /* table of filenames */
        !           175: static struct ohash     strings; /* table of all strings */
        !           176: static struct of       *ofs = NULL; /* vector of files to parse */
        !           177: static struct str      *words = NULL; /* word list in current parse */
        !           178: static sqlite3         *db = NULL; /* current database */
        !           179: static sqlite3_stmt    *stmts[STMT__MAX]; /* current statements */
1.25      schwarze  180:
                    181: static const struct mdoc_handler mdocs[MDOC_MAX] = {
                    182:        { NULL, 0, 0 },  /* Ap */
                    183:        { NULL, 0, 0 },  /* Dd */
                    184:        { NULL, 0, 0 },  /* Dt */
                    185:        { NULL, 0, 0 },  /* Os */
1.50    ! kristaps  186:        { parse_mdoc_Sh, TYPE_Sh, MDOCF_CHILD }, /* Sh */
        !           187:        { parse_mdoc_head, TYPE_Ss, MDOCF_CHILD }, /* Ss */
1.25      schwarze  188:        { NULL, 0, 0 },  /* Pp */
                    189:        { NULL, 0, 0 },  /* D1 */
                    190:        { NULL, 0, 0 },  /* Dl */
                    191:        { NULL, 0, 0 },  /* Bd */
                    192:        { NULL, 0, 0 },  /* Ed */
                    193:        { NULL, 0, 0 },  /* Bl */
                    194:        { NULL, 0, 0 },  /* El */
                    195:        { NULL, 0, 0 },  /* It */
                    196:        { NULL, 0, 0 },  /* Ad */
                    197:        { NULL, TYPE_An, MDOCF_CHILD },  /* An */
                    198:        { NULL, TYPE_Ar, MDOCF_CHILD },  /* Ar */
                    199:        { NULL, TYPE_Cd, MDOCF_CHILD },  /* Cd */
                    200:        { NULL, TYPE_Cm, MDOCF_CHILD },  /* Cm */
                    201:        { NULL, TYPE_Dv, MDOCF_CHILD },  /* Dv */
                    202:        { NULL, TYPE_Er, MDOCF_CHILD },  /* Er */
                    203:        { NULL, TYPE_Ev, MDOCF_CHILD },  /* Ev */
                    204:        { NULL, 0, 0 },  /* Ex */
                    205:        { NULL, TYPE_Fa, MDOCF_CHILD },  /* Fa */
1.50    ! kristaps  206:        { parse_mdoc_Fd, TYPE_In, 0 },  /* Fd */
1.25      schwarze  207:        { NULL, TYPE_Fl, MDOCF_CHILD },  /* Fl */
1.50    ! kristaps  208:        { parse_mdoc_Fn, 0, 0 },  /* Fn */
1.25      schwarze  209:        { NULL, TYPE_Ft, MDOCF_CHILD },  /* Ft */
                    210:        { NULL, TYPE_Ic, MDOCF_CHILD },  /* Ic */
1.50    ! kristaps  211:        { parse_mdoc_In, TYPE_In, MDOCF_CHILD },  /* In */
1.25      schwarze  212:        { NULL, TYPE_Li, MDOCF_CHILD },  /* Li */
1.50    ! kristaps  213:        { parse_mdoc_Nd, TYPE_Nd, MDOCF_CHILD },  /* Nd */
        !           214:        { parse_mdoc_Nm, TYPE_Nm, MDOCF_CHILD },  /* Nm */
1.25      schwarze  215:        { NULL, 0, 0 },  /* Op */
                    216:        { NULL, 0, 0 },  /* Ot */
                    217:        { NULL, TYPE_Pa, MDOCF_CHILD },  /* Pa */
                    218:        { NULL, 0, 0 },  /* Rv */
1.50    ! kristaps  219:        { parse_mdoc_St, TYPE_St, 0 },  /* St */
1.25      schwarze  220:        { NULL, TYPE_Va, MDOCF_CHILD },  /* Va */
1.50    ! kristaps  221:        { parse_mdoc_body, TYPE_Va, MDOCF_CHILD },  /* Vt */
        !           222:        { parse_mdoc_Xr, TYPE_Xr, 0 },  /* Xr */
1.25      schwarze  223:        { NULL, 0, 0 },  /* %A */
                    224:        { NULL, 0, 0 },  /* %B */
                    225:        { NULL, 0, 0 },  /* %D */
                    226:        { NULL, 0, 0 },  /* %I */
                    227:        { NULL, 0, 0 },  /* %J */
                    228:        { NULL, 0, 0 },  /* %N */
                    229:        { NULL, 0, 0 },  /* %O */
                    230:        { NULL, 0, 0 },  /* %P */
                    231:        { NULL, 0, 0 },  /* %R */
                    232:        { NULL, 0, 0 },  /* %T */
                    233:        { NULL, 0, 0 },  /* %V */
                    234:        { NULL, 0, 0 },  /* Ac */
                    235:        { NULL, 0, 0 },  /* Ao */
                    236:        { NULL, 0, 0 },  /* Aq */
                    237:        { NULL, TYPE_At, MDOCF_CHILD },  /* At */
                    238:        { NULL, 0, 0 },  /* Bc */
                    239:        { NULL, 0, 0 },  /* Bf */
                    240:        { NULL, 0, 0 },  /* Bo */
                    241:        { NULL, 0, 0 },  /* Bq */
                    242:        { NULL, TYPE_Bsx, MDOCF_CHILD },  /* Bsx */
                    243:        { NULL, TYPE_Bx, MDOCF_CHILD },  /* Bx */
                    244:        { NULL, 0, 0 },  /* Db */
                    245:        { NULL, 0, 0 },  /* Dc */
                    246:        { NULL, 0, 0 },  /* Do */
                    247:        { NULL, 0, 0 },  /* Dq */
                    248:        { NULL, 0, 0 },  /* Ec */
                    249:        { NULL, 0, 0 },  /* Ef */
                    250:        { NULL, TYPE_Em, MDOCF_CHILD },  /* Em */
                    251:        { NULL, 0, 0 },  /* Eo */
                    252:        { NULL, TYPE_Fx, MDOCF_CHILD },  /* Fx */
                    253:        { NULL, TYPE_Ms, MDOCF_CHILD },  /* Ms */
                    254:        { NULL, 0, 0 },  /* No */
                    255:        { NULL, 0, 0 },  /* Ns */
                    256:        { NULL, TYPE_Nx, MDOCF_CHILD },  /* Nx */
                    257:        { NULL, TYPE_Ox, MDOCF_CHILD },  /* Ox */
                    258:        { NULL, 0, 0 },  /* Pc */
                    259:        { NULL, 0, 0 },  /* Pf */
                    260:        { NULL, 0, 0 },  /* Po */
                    261:        { NULL, 0, 0 },  /* Pq */
                    262:        { NULL, 0, 0 },  /* Qc */
                    263:        { NULL, 0, 0 },  /* Ql */
                    264:        { NULL, 0, 0 },  /* Qo */
                    265:        { NULL, 0, 0 },  /* Qq */
                    266:        { NULL, 0, 0 },  /* Re */
                    267:        { NULL, 0, 0 },  /* Rs */
                    268:        { NULL, 0, 0 },  /* Sc */
                    269:        { NULL, 0, 0 },  /* So */
                    270:        { NULL, 0, 0 },  /* Sq */
                    271:        { NULL, 0, 0 },  /* Sm */
                    272:        { NULL, 0, 0 },  /* Sx */
                    273:        { NULL, TYPE_Sy, MDOCF_CHILD },  /* Sy */
                    274:        { NULL, TYPE_Tn, MDOCF_CHILD },  /* Tn */
                    275:        { NULL, 0, 0 },  /* Ux */
                    276:        { NULL, 0, 0 },  /* Xc */
                    277:        { NULL, 0, 0 },  /* Xo */
1.50    ! kristaps  278:        { parse_mdoc_head, TYPE_Fn, 0 },  /* Fo */
1.25      schwarze  279:        { NULL, 0, 0 },  /* Fc */
                    280:        { NULL, 0, 0 },  /* Oo */
                    281:        { NULL, 0, 0 },  /* Oc */
                    282:        { NULL, 0, 0 },  /* Bk */
                    283:        { NULL, 0, 0 },  /* Ek */
                    284:        { NULL, 0, 0 },  /* Bt */
                    285:        { NULL, 0, 0 },  /* Hf */
                    286:        { NULL, 0, 0 },  /* Fr */
                    287:        { NULL, 0, 0 },  /* Ud */
                    288:        { NULL, TYPE_Lb, MDOCF_CHILD },  /* Lb */
                    289:        { NULL, 0, 0 },  /* Lp */
                    290:        { NULL, TYPE_Lk, MDOCF_CHILD },  /* Lk */
                    291:        { NULL, TYPE_Mt, MDOCF_CHILD },  /* Mt */
                    292:        { NULL, 0, 0 },  /* Brq */
                    293:        { NULL, 0, 0 },  /* Bro */
                    294:        { NULL, 0, 0 },  /* Brc */
                    295:        { NULL, 0, 0 },  /* %C */
                    296:        { NULL, 0, 0 },  /* Es */
                    297:        { NULL, 0, 0 },  /* En */
                    298:        { NULL, TYPE_Dx, MDOCF_CHILD },  /* Dx */
                    299:        { NULL, 0, 0 },  /* %Q */
                    300:        { NULL, 0, 0 },  /* br */
                    301:        { NULL, 0, 0 },  /* sp */
                    302:        { NULL, 0, 0 },  /* %U */
                    303:        { NULL, 0, 0 },  /* Ta */
1.1       kristaps  304: };
                    305:
                    306: int
                    307: main(int argc, char *argv[])
                    308: {
1.50    ! kristaps  309:        char              cwd[MAXPATHLEN];
        !           310:        int               ch, rc, fd, i;
        !           311:        size_t            j, sz;
        !           312:        const char       *dir;
        !           313:        struct str       *s;
        !           314:        struct mchars    *mc;
        !           315:        struct manpaths   dirs;
        !           316:        struct mparse    *mp;
        !           317:        struct ohash_info ino_info, filename_info, str_info;
        !           318:
        !           319:        memset(stmts, 0, STMT__MAX * sizeof(sqlite3_stmt *));
        !           320:        memset(&dirs, 0, sizeof(struct manpaths));
        !           321:
        !           322:        ino_info.halloc = filename_info.halloc =
        !           323:                str_info.halloc = hash_halloc;
        !           324:        ino_info.hfree = filename_info.hfree =
        !           325:                str_info.hfree = hash_free;
        !           326:        ino_info.alloc = filename_info.alloc =
        !           327:                str_info.alloc = hash_alloc;
        !           328:
        !           329:        ino_info.key_offset = offsetof(struct of, id);
        !           330:        filename_info.key_offset = offsetof(struct of, file);
        !           331:        str_info.key_offset = offsetof(struct str, key);
1.1       kristaps  332:
                    333:        progname = strrchr(argv[0], '/');
                    334:        if (progname == NULL)
                    335:                progname = argv[0];
                    336:        else
                    337:                ++progname;
                    338:
1.50    ! kristaps  339:        /*
        !           340:         * Remember where we started by keeping a fd open to the origin
        !           341:         * path component: throughout this utility, we chdir() a lot to
        !           342:         * handle relative paths, and by doing this, we can return to
        !           343:         * the starting point.
        !           344:         */
        !           345:        if (NULL == getcwd(cwd, MAXPATHLEN)) {
        !           346:                perror(NULL);
        !           347:                return(EXIT_FAILURE);
        !           348:        } else if (-1 == (fd = open(cwd, O_RDONLY, 0))) {
        !           349:                perror(cwd);
        !           350:                return(EXIT_FAILURE);
        !           351:        }
        !           352:
        !           353:        /*
        !           354:         * We accept a few different invocations.
        !           355:         * The CHECKOP macro makes sure that invocation styles don't
        !           356:         * clobber each other.
        !           357:         */
        !           358: #define        CHECKOP(_op, _ch) do \
        !           359:        if (OP_DEFAULT != (_op)) { \
        !           360:                fprintf(stderr, "-%c: Conflicting option\n", (_ch)); \
        !           361:                goto usage; \
        !           362:        } while (/*CONSTCOND*/0)
1.10      kristaps  363:
1.50    ! kristaps  364:        dir = NULL;
1.38      schwarze  365:        op = OP_DEFAULT;
1.1       kristaps  366:
1.50    ! kristaps  367:        while (-1 != (ch = getopt(argc, argv, "aC:d:ntu:vW")))
1.1       kristaps  368:                switch (ch) {
1.12      schwarze  369:                case ('a'):
                    370:                        use_all = 1;
                    371:                        break;
1.34      schwarze  372:                case ('C'):
1.50    ! kristaps  373:                        CHECKOP(op, ch);
1.38      schwarze  374:                        dir = optarg;
                    375:                        op = OP_CONFFILE;
1.34      schwarze  376:                        break;
1.5       kristaps  377:                case ('d'):
1.50    ! kristaps  378:                        CHECKOP(op, ch);
1.5       kristaps  379:                        dir = optarg;
                    380:                        op = OP_UPDATE;
                    381:                        break;
1.50    ! kristaps  382:                case ('n'):
        !           383:                        nodb = 1;
        !           384:                        break;
1.38      schwarze  385:                case ('t'):
1.50    ! kristaps  386:                        CHECKOP(op, ch);
1.38      schwarze  387:                        dup2(STDOUT_FILENO, STDERR_FILENO);
                    388:                        op = OP_TEST;
1.50    ! kristaps  389:                        nodb = warnings = 1;
1.38      schwarze  390:                        break;
1.5       kristaps  391:                case ('u'):
1.50    ! kristaps  392:                        CHECKOP(op, ch);
1.5       kristaps  393:                        dir = optarg;
                    394:                        op = OP_DELETE;
                    395:                        break;
                    396:                case ('v'):
                    397:                        verb++;
                    398:                        break;
1.38      schwarze  399:                case ('W'):
                    400:                        warnings = 1;
                    401:                        break;
1.1       kristaps  402:                default:
1.38      schwarze  403:                        goto usage;
1.1       kristaps  404:                }
                    405:
                    406:        argc -= optind;
                    407:        argv += optind;
                    408:
1.38      schwarze  409:        if (OP_CONFFILE == op && argc > 0) {
1.50    ! kristaps  410:                fprintf(stderr, "-C: Too many arguments\n");
1.38      schwarze  411:                goto usage;
                    412:        }
                    413:
1.50    ! kristaps  414:        rc = 1;
        !           415:        mp = mparse_alloc(MPARSE_AUTO,
        !           416:                MANDOCLEVEL_FATAL, NULL, NULL, NULL);
        !           417:        mc = mchars_alloc();
        !           418:
        !           419:        ohash_init(&strings, 6, &str_info);
        !           420:        ohash_init(&inos, 6, &ino_info);
        !           421:        ohash_init(&filenames, 6, &filename_info);
        !           422:
        !           423:        if (OP_UPDATE == op || OP_DELETE == op || OP_TEST == op) {
        !           424:                /*
        !           425:                 * Force processing all files.
        !           426:                 */
        !           427:                use_all = 1;
        !           428:                if (NULL == dir)
        !           429:                        dir = cwd;
        !           430:                /*
        !           431:                 * All of these deal with a specific directory.
        !           432:                 * Jump into that directory then collect files specified
        !           433:                 * on the command-line.
        !           434:                 */
        !           435:                if (0 == path_reset(cwd, fd, dir))
        !           436:                        goto out;
        !           437:                for (i = 0; i < argc; i++)
        !           438:                        filescan(argv[i], dir);
        !           439:                if (0 == dbopen(dir, 1))
        !           440:                        goto out;
        !           441:                if (OP_TEST != op)
        !           442:                        dbprune(dir);
        !           443:                if (OP_DELETE != op)
        !           444:                        rc = ofmerge(mc, mp, dir);
        !           445:                dbclose(dir, 1);
        !           446:        } else {
        !           447:                /*
        !           448:                 * If we have arguments, use them as our manpaths.
        !           449:                 * If we don't, grok from manpath(1) or however else
        !           450:                 * manpath_parse() wants to do it.
        !           451:                 */
        !           452:                if (argc > 0) {
        !           453:                        dirs.paths = mandoc_calloc
        !           454:                                (argc, sizeof(char *));
        !           455:                        dirs.sz = (size_t)argc;
        !           456:                        for (i = 0; i < argc; i++)
        !           457:                                dirs.paths[i] = mandoc_strdup(argv[i]);
        !           458:                } else
        !           459:                        manpath_parse(&dirs, dir, NULL, NULL);
        !           460:
        !           461:                /*
        !           462:                 * First scan the tree rooted at a base directory.
        !           463:                 * Then whak its database (if one exists), parse, and
        !           464:                 * build up the database.
        !           465:                 * Ignore zero-length directories and strip trailing
        !           466:                 * slashes.
        !           467:                 */
        !           468:                for (j = 0; j < dirs.sz; j++) {
        !           469:                        sz = strlen(dirs.paths[j]);
        !           470:                        if (sz && '/' == dirs.paths[j][sz - 1])
        !           471:                                dirs.paths[j][--sz] = '\0';
        !           472:                        if (0 == sz)
        !           473:                                continue;
        !           474:                        if (0 == path_reset(cwd, fd, dirs.paths[j]))
        !           475:                                goto out;
        !           476:                        if (0 == treescan(dirs.paths[j]))
        !           477:                                goto out;
        !           478:                        if (0 == path_reset(cwd, fd, dirs.paths[j]))
        !           479:                                goto out;
        !           480:                        if (0 == dbopen(dirs.paths[j], 0))
        !           481:                                goto out;
        !           482:                        if (0 == ofmerge(mc, mp, dirs.paths[j]))
        !           483:                                goto out;
        !           484:                        dbclose(dirs.paths[j], 0);
        !           485:                        offree();
        !           486:                        ohash_delete(&inos);
        !           487:                        ohash_init(&inos, 6, &ino_info);
        !           488:                        ohash_delete(&filenames);
        !           489:                        ohash_init(&filenames, 6, &filename_info);
        !           490:                }
        !           491:        }
        !           492: out:
        !           493:        close(fd);
        !           494:        manpath_free(&dirs);
        !           495:        mchars_free(mc);
        !           496:        mparse_free(mp);
        !           497:        for (s = ohash_first(&strings, &ch);
        !           498:                        NULL != s; s = ohash_next(&strings, &ch)) {
        !           499:                if (s->utf8 != s->key)
        !           500:                        free(s->utf8);
        !           501:                free(s);
        !           502:        }
        !           503:        ohash_delete(&strings);
        !           504:        ohash_delete(&inos);
        !           505:        ohash_delete(&filenames);
        !           506:        offree();
        !           507:        return(rc ? EXIT_SUCCESS : EXIT_FAILURE);
        !           508: usage:
        !           509:        fprintf(stderr, "usage: %s [-anvW] [-C file]\n"
        !           510:                        "       %s [-anvW] dir ...\n"
        !           511:                        "       %s [-nvW] -d dir [file ...]\n"
        !           512:                        "       %s [-nvW] -u dir [file ...]\n"
        !           513:                        "       %s -t file ...\n",
        !           514:                       progname, progname, progname,
        !           515:                       progname, progname);
        !           516:
        !           517:        return(EXIT_FAILURE);
        !           518: }
        !           519:
        !           520: /*
        !           521:  * Scan a directory tree rooted at "base" for manpages.
        !           522:  * We use fts(), scanning directory parts along the way for clues to our
        !           523:  * section and architecture.
        !           524:  *
        !           525:  * If use_all has been specified, grok all files.
        !           526:  * If not, sanitise paths to the following:
        !           527:  *
        !           528:  *   [./]man*[/<arch>]/<name>.<section>
        !           529:  *   or
        !           530:  *   [./]cat<section>[/<arch>]/<name>.0
        !           531:  *
        !           532:  * TODO: accomodate for multi-language directories.
        !           533:  */
        !           534: static int
        !           535: treescan(const char *base)
        !           536: {
        !           537:        FTS             *f;
        !           538:        FTSENT          *ff;
        !           539:        int              dform;
        !           540:        char            *sec;
        !           541:        const char      *dsec, *arch, *cp, *name, *path;
        !           542:        const char      *argv[2];
        !           543:
        !           544:        argv[0] = ".";
        !           545:        argv[1] = (char *)NULL;
        !           546:
        !           547:        /*
        !           548:         * Walk through all components under the directory, using the
        !           549:         * logical descent of files.
        !           550:         */
        !           551:        f = fts_open((char * const *)argv, FTS_LOGICAL, NULL);
        !           552:        if (NULL == f) {
        !           553:                perror(base);
        !           554:                return(0);
        !           555:        }
        !           556:
        !           557:        dsec = arch = NULL;
        !           558:        dform = FORM_NONE;
        !           559:
        !           560:        while (NULL != (ff = fts_read(f))) {
        !           561:                path = ff->fts_path + 2;
        !           562:                /*
        !           563:                 * If we're a regular file, add an "of" by using the
        !           564:                 * stored directory data and handling the filename.
        !           565:                 * Disallow duplicate (hard-linked) files.
        !           566:                 */
        !           567:                if (FTS_F == ff->fts_info) {
        !           568:                        if ( ! use_all && ff->fts_level < 2) {
        !           569:                                WARNING(path, base, "Extraneous file");
        !           570:                                continue;
        !           571:                        } else if (inocheck(ff->fts_statp)) {
        !           572:                                WARNING(path, base, "Duplicate file");
        !           573:                                continue;
        !           574:                        }
        !           575:
        !           576:                        cp = ff->fts_name;
        !           577:
        !           578:                        if (0 == strcmp(cp, "mandocdb.db")) {
        !           579:                                WARNING(path, base, "Skip database");
        !           580:                                continue;
        !           581:                        } else if (NULL != (cp = strrchr(cp, '.'))) {
        !           582:                                if (0 == strcmp(cp + 1, "html")) {
        !           583:                                        WARNING(path, base, "Skip html");
        !           584:                                        continue;
        !           585:                                } else if (0 == strcmp(cp + 1, "gz")) {
        !           586:                                        WARNING(path, base, "Skip gz");
        !           587:                                        continue;
        !           588:                                } else if (0 == strcmp(cp + 1, "ps")) {
        !           589:                                        WARNING(path, base, "Skip ps");
        !           590:                                        continue;
        !           591:                                } else if (0 == strcmp(cp + 1, "pdf")) {
        !           592:                                        WARNING(path, base, "Skip pdf");
        !           593:                                        continue;
        !           594:                                }
        !           595:                        }
1.1       kristaps  596:
1.50    ! kristaps  597:                        if (NULL != (sec = strrchr(ff->fts_name, '.'))) {
        !           598:                                *sec = '\0';
        !           599:                                sec = stradd(sec + 1);
        !           600:                        }
        !           601:                        name = stradd(ff->fts_name);
        !           602:                        ofadd(base, dform, path,
        !           603:                                name, dsec, sec, arch, ff->fts_statp);
        !           604:                        continue;
        !           605:                } else if (FTS_D != ff->fts_info &&
        !           606:                                FTS_DP != ff->fts_info)
        !           607:                        continue;
1.1       kristaps  608:
1.50    ! kristaps  609:                switch (ff->fts_level) {
        !           610:                case (0):
        !           611:                        /* Ignore the root directory. */
        !           612:                        break;
        !           613:                case (1):
        !           614:                        /*
        !           615:                         * This might contain manX/ or catX/.
        !           616:                         * Try to infer this from the name.
        !           617:                         * If we're not in use_all, enforce it.
        !           618:                         */
        !           619:                        dsec = NULL;
        !           620:                        dform = FORM_NONE;
        !           621:                        cp = ff->fts_name;
        !           622:                        if (FTS_DP == ff->fts_info)
        !           623:                                break;
1.1       kristaps  624:
1.50    ! kristaps  625:                        if (0 == strncmp(cp, "man", 3)) {
        !           626:                                dform = FORM_SRC;
        !           627:                                dsec = stradd(cp + 3);
        !           628:                        } else if (0 == strncmp(cp, "cat", 3)) {
        !           629:                                dform = FORM_CAT;
        !           630:                                dsec = stradd(cp + 3);
        !           631:                        }
1.1       kristaps  632:
1.50    ! kristaps  633:                        if (NULL != dsec || use_all)
        !           634:                                break;
1.1       kristaps  635:
1.50    ! kristaps  636:                        WARNING(path, base, "Unknown directory part");
        !           637:                        fts_set(f, ff, FTS_SKIP);
        !           638:                        break;
        !           639:                case (2):
        !           640:                        /*
        !           641:                         * Possibly our architecture.
        !           642:                         * If we're descending, keep tabs on it.
        !           643:                         */
        !           644:                        arch = NULL;
        !           645:                        if (FTS_DP != ff->fts_info && NULL != dsec)
        !           646:                                arch = stradd(ff->fts_name);
        !           647:                        break;
        !           648:                default:
        !           649:                        if (FTS_DP == ff->fts_info || use_all)
        !           650:                                break;
        !           651:                        WARNING(path, base, "Extraneous directory part");
        !           652:                        fts_set(f, ff, FTS_SKIP);
        !           653:                        break;
1.5       kristaps  654:                }
1.50    ! kristaps  655:        }
        !           656:
        !           657:        fts_close(f);
        !           658:        return(1);
        !           659: }
1.5       kristaps  660:
1.50    ! kristaps  661: /*
        !           662:  * Add a file to the file vector.
        !           663:  * Do not verify that it's a "valid" looking manpage (we'll do that
        !           664:  * later).
        !           665:  *
        !           666:  * Try to infer the manual section, architecture, and page name from the
        !           667:  * path, assuming it looks like
        !           668:  *
        !           669:  *   [./]man*[/<arch>]/<name>.<section>
        !           670:  *   or
        !           671:  *   [./]cat<section>[/<arch>]/<name>.0
        !           672:  *
        !           673:  * Stuff this information directly into the "of" vector.
        !           674:  * See treescan() for the fts(3) version of this.
        !           675:  */
        !           676: static void
        !           677: filescan(const char *file, const char *base)
        !           678: {
        !           679:        const char      *sec, *arch, *name, *dsec;
        !           680:        char            *p, *start, *buf;
        !           681:        int              dform;
        !           682:        struct stat      st;
1.5       kristaps  683:
1.50    ! kristaps  684:        assert(use_all);
1.5       kristaps  685:
1.50    ! kristaps  686:        if (0 == strncmp(file, "./", 2))
        !           687:                file += 2;
1.5       kristaps  688:
1.50    ! kristaps  689:        if (-1 == stat(file, &st)) {
        !           690:                WARNING(file, base, "%s", strerror(errno));
        !           691:                return;
        !           692:        } else if ( ! (S_IFREG & st.st_mode)) {
        !           693:                WARNING(file, base, "Not a regular file");
        !           694:                return;
        !           695:        } else if (inocheck(&st)) {
        !           696:                WARNING(file, base, "Duplicate file");
        !           697:                return;
        !           698:        }
1.5       kristaps  699:
1.50    ! kristaps  700:        buf = mandoc_strdup(file);
        !           701:        start = buf;
        !           702:        sec = arch = name = dsec = NULL;
        !           703:        dform = FORM_NONE;
1.17      schwarze  704:
1.50    ! kristaps  705:        /*
        !           706:         * First try to guess our directory structure.
        !           707:         * If we find a separator, try to look for man* or cat*.
        !           708:         * If we find one of these and what's underneath is a directory,
        !           709:         * assume it's an architecture.
        !           710:         */
        !           711:        if (NULL != (p = strchr(start, '/'))) {
        !           712:                *p++ = '\0';
        !           713:                if (0 == strncmp(start, "man", 3)) {
        !           714:                        dform = FORM_SRC;
        !           715:                        dsec = start + 3;
        !           716:                } else if (0 == strncmp(start, "cat", 3)) {
        !           717:                        dform = FORM_CAT;
        !           718:                        dsec = start + 3;
1.17      schwarze  719:                }
1.5       kristaps  720:
1.50    ! kristaps  721:                start = p;
        !           722:                if (NULL != dsec && NULL != (p = strchr(start, '/'))) {
        !           723:                        *p++ = '\0';
        !           724:                        arch = start;
        !           725:                        start = p;
        !           726:                }
        !           727:        }
        !           728:
        !           729:        /*
        !           730:         * Now check the file suffix.
        !           731:         * Suffix of `.0' indicates a catpage, `.1-9' is a manpage.
        !           732:         */
        !           733:        p = strrchr(start, '\0');
        !           734:        while (p-- > start && '/' != *p && '.' != *p)
        !           735:                /* Loop. */ ;
        !           736:
        !           737:        if ('.' == *p) {
        !           738:                *p++ = '\0';
        !           739:                sec = p;
1.5       kristaps  740:        }
                    741:
1.10      kristaps  742:        /*
1.50    ! kristaps  743:         * Now try to parse the name.
        !           744:         * Use the filename portion of the path.
1.10      kristaps  745:         */
1.50    ! kristaps  746:        name = start;
        !           747:        if (NULL != (p = strrchr(start, '/'))) {
        !           748:                name = p + 1;
        !           749:                *p = '\0';
        !           750:        }
        !           751:
        !           752:        ofadd(base, dform, file, name, dsec, sec, arch, &st);
        !           753:        free(buf);
        !           754: }
        !           755:
        !           756: /*
        !           757:  * See fileadd().
        !           758:  */
        !           759: static int
        !           760: filecheck(const char *name)
        !           761: {
        !           762:        unsigned int     index;
1.10      kristaps  763:
1.50    ! kristaps  764:        index = ohash_qlookup(&filenames, name);
        !           765:        return(NULL != ohash_find(&filenames, index));
        !           766: }
1.10      kristaps  767:
1.50    ! kristaps  768: /*
        !           769:  * Use the standard hashing mechanism (K&R) to see if the given filename
        !           770:  * already exists.
        !           771:  */
        !           772: static void
        !           773: fileadd(struct of *of)
        !           774: {
        !           775:        unsigned int     index;
1.1       kristaps  776:
1.50    ! kristaps  777:        index = ohash_qlookup(&filenames, of->file);
        !           778:        assert(NULL == ohash_find(&filenames, index));
        !           779:        ohash_insert(&filenames, index, of);
        !           780: }
1.3       kristaps  781:
1.50    ! kristaps  782: /*
        !           783:  * See inoadd().
        !           784:  */
        !           785: static int
        !           786: inocheck(const struct stat *st)
        !           787: {
        !           788:        struct id        id;
        !           789:        uint32_t         hash;
        !           790:        unsigned int     index;
        !           791:
        !           792:        memset(&id, 0, sizeof(id));
        !           793:        id.ino = hash = st->st_ino;
        !           794:        id.dev = st->st_dev;
        !           795:        index = ohash_lookup_memory
        !           796:                (&inos, (char *)&id, sizeof(id), hash);
1.13      schwarze  797:
1.50    ! kristaps  798:        return(NULL != ohash_find(&inos, index));
        !           799: }
1.5       kristaps  800:
1.50    ! kristaps  801: /*
        !           802:  * The hashing function used here is quite simple: simply take the inode
        !           803:  * and use uint32_t of its bits.
        !           804:  * Then when we do the lookup, use both the inode and device identifier.
        !           805:  */
        !           806: static void
        !           807: inoadd(const struct stat *st, struct of *of)
        !           808: {
        !           809:        uint32_t         hash;
        !           810:        unsigned int     index;
1.1       kristaps  811:
1.50    ! kristaps  812:        of->id.ino = hash = st->st_ino;
        !           813:        of->id.dev = st->st_dev;
        !           814:        index = ohash_lookup_memory
        !           815:                (&inos, (char *)&of->id, sizeof(of->id), hash);
1.1       kristaps  816:
1.50    ! kristaps  817:        assert(NULL == ohash_find(&inos, index));
        !           818:        ohash_insert(&inos, index, of);
        !           819: }
1.35      kristaps  820:
1.50    ! kristaps  821: static void
        !           822: ofadd(const char *base, int dform, const char *file,
        !           823:                const char *name, const char *dsec, const char *sec,
        !           824:                const char *arch, const struct stat *st)
        !           825: {
        !           826:        struct of       *of;
        !           827:        int              sform;
        !           828:
        !           829:        assert(NULL != file);
        !           830:
        !           831:        if (NULL == name)
        !           832:                name = "";
        !           833:        if (NULL == sec)
        !           834:                sec = "";
        !           835:        if (NULL == dsec)
        !           836:                dsec = "";
        !           837:        if (NULL == arch)
        !           838:                arch = "";
        !           839:
        !           840:        sform = FORM_NONE;
        !           841:        if (NULL != sec && *sec <= '9' && *sec >= '1')
        !           842:                sform = FORM_SRC;
        !           843:        else if (NULL != sec && *sec == '0') {
        !           844:                sec = dsec;
        !           845:                sform = FORM_CAT;
        !           846:        }
        !           847:
        !           848:        of = mandoc_calloc(1, sizeof(struct of));
        !           849:        strlcpy(of->file, file, MAXPATHLEN);
        !           850:        of->name = name;
        !           851:        of->sec = sec;
        !           852:        of->dsec = dsec;
        !           853:        of->arch = arch;
        !           854:        of->sform = sform;
        !           855:        of->dform = dform;
        !           856:        of->next = ofs;
        !           857:        ofs = of;
1.3       kristaps  858:
1.50    ! kristaps  859:        /*
        !           860:         * Add to unique identifier hash.
        !           861:         * Then if it's a source manual and we're going to use source in
        !           862:         * favour of catpages, add it to that hash.
        !           863:         */
        !           864:        inoadd(st, of);
        !           865:        fileadd(of);
        !           866: }
1.3       kristaps  867:
1.50    ! kristaps  868: static void
        !           869: offree(void)
        !           870: {
        !           871:        struct of       *of;
1.3       kristaps  872:
1.50    ! kristaps  873:        while (NULL != (of = ofs)) {
        !           874:                ofs = of->next;
        !           875:                free(of);
        !           876:        }
        !           877: }
1.38      schwarze  878:
1.50    ! kristaps  879: /*
        !           880:  * Run through the files in the global vector "ofs" and add them to the
        !           881:  * database specified in "base".
        !           882:  *
        !           883:  * This handles the parsing scheme itself, using the cues of directory
        !           884:  * and filename to determine whether the file is parsable or not.
        !           885:  */
        !           886: static int
        !           887: ofmerge(struct mchars *mc, struct mparse *mp, const char *base)
        !           888: {
        !           889:        int              form;
        !           890:        size_t           sz;
1.3       kristaps  891:        struct mdoc     *mdoc;
                    892:        struct man      *man;
1.50    ! kristaps  893:        char             buf[MAXPATHLEN];
        !           894:        char            *bufp;
        !           895:        const char      *msec, *march, *mtitle, *cp;
        !           896:        struct of       *of;
        !           897:        enum mandoclevel lvl;
        !           898:
        !           899:        for (of = ofs; NULL != of; of = of->next) {
        !           900:                /*
        !           901:                 * If we're a catpage (as defined by our path), then see
        !           902:                 * if a manpage exists by the same name (ignoring the
        !           903:                 * suffix).
        !           904:                 * If it does, then we want to use it instead of our
        !           905:                 * own.
        !           906:                 */
        !           907:                if ( ! use_all && FORM_CAT == of->dform) {
        !           908:                        sz = strlcpy(buf, of->file, MAXPATHLEN);
        !           909:                        if (sz >= MAXPATHLEN) {
        !           910:                                WARNING(of->file, base,
        !           911:                                        "Filename too long");
        !           912:                                continue;
        !           913:                        }
        !           914:                        bufp = strstr(buf, "cat");
        !           915:                        assert(NULL != bufp);
        !           916:                        memcpy(bufp, "man", 3);
        !           917:                        if (NULL != (bufp = strrchr(buf, '.')))
        !           918:                                *++bufp = '\0';
        !           919:                        strlcat(buf, of->dsec, MAXPATHLEN);
        !           920:                        if (filecheck(buf)) {
        !           921:                                WARNING(of->file, base, "Man "
        !           922:                                        "source exists: %s", buf);
        !           923:                                continue;
        !           924:                        }
        !           925:                }
        !           926:
        !           927:                words = NULL;
        !           928:                mparse_reset(mp);
        !           929:                mdoc = NULL;
        !           930:                man = NULL;
        !           931:                form = 0;
        !           932:                msec = of->dsec;
        !           933:                march = of->arch;
        !           934:                mtitle = of->name;
1.14      schwarze  935:
                    936:                /*
1.33      schwarze  937:                 * Try interpreting the file as mdoc(7) or man(7)
                    938:                 * source code, unless it is already known to be
                    939:                 * formatted.  Fall back to formatted mode.
1.14      schwarze  940:                 */
1.50    ! kristaps  941:                if (FORM_SRC == of->dform || FORM_SRC == of->sform) {
        !           942:                        lvl = mparse_readfd(mp, -1, of->file);
        !           943:                        if (lvl < MANDOCLEVEL_FATAL)
        !           944:                                mparse_result(mp, &mdoc, &man);
        !           945:                }
1.14      schwarze  946:
                    947:                if (NULL != mdoc) {
1.50    ! kristaps  948:                        form = 1;
1.14      schwarze  949:                        msec = mdoc_meta(mdoc)->msec;
1.38      schwarze  950:                        march = mdoc_meta(mdoc)->arch;
1.14      schwarze  951:                        mtitle = mdoc_meta(mdoc)->title;
                    952:                } else if (NULL != man) {
1.50    ! kristaps  953:                        form = 1;
1.14      schwarze  954:                        msec = man_meta(man)->msec;
1.38      schwarze  955:                        march = "";
1.14      schwarze  956:                        mtitle = man_meta(man)->title;
1.50    ! kristaps  957:                }
        !           958:
        !           959:                if (NULL == msec)
        !           960:                        msec = "";
        !           961:                if (NULL == march)
        !           962:                        march = "";
        !           963:                if (NULL == mtitle)
        !           964:                        mtitle = "";
1.1       kristaps  965:
1.12      schwarze  966:                /*
1.44      kristaps  967:                 * Check whether the manual section given in a file
                    968:                 * agrees with the directory where the file is located.
                    969:                 * Some manuals have suffixes like (3p) on their
                    970:                 * section number either inside the file or in the
                    971:                 * directory name, some are linked into more than one
                    972:                 * section, like encrypt(1) = makekey(8).  Do not skip
                    973:                 * manuals for such reasons.
1.12      schwarze  974:                 */
1.50    ! kristaps  975:                if ( ! use_all && form && strcasecmp(msec, of->dsec))
        !           976:                        WARNING(of->file, base, "Section \"%s\" "
        !           977:                                "manual in %s directory",
        !           978:                                msec, of->dsec);
1.12      schwarze  979:
1.42      schwarze  980:                /*
                    981:                 * Manual page directories exist for each kernel
                    982:                 * architecture as returned by machine(1).
                    983:                 * However, many manuals only depend on the
                    984:                 * application architecture as returned by arch(1).
                    985:                 * For example, some (2/ARM) manuals are shared
                    986:                 * across the "armish" and "zaurus" kernel
                    987:                 * architectures.
                    988:                 * A few manuals are even shared across completely
                    989:                 * different architectures, for example fdformat(1)
                    990:                 * on amd64, i386, sparc, and sparc64.
                    991:                 * Thus, warn about architecture mismatches,
                    992:                 * but don't skip manuals for this reason.
                    993:                 */
1.50    ! kristaps  994:                if ( ! use_all && strcasecmp(march, of->arch))
        !           995:                        WARNING(of->file, base, "Architecture \"%s\" "
1.47      schwarze  996:                                "manual in \"%s\" directory",
1.45      kristaps  997:                                march, of->arch);
1.12      schwarze  998:
1.50    ! kristaps  999:                putkey(of, of->name, TYPE_Nm);
1.12      schwarze 1000:
1.50    ! kristaps 1001:                if (NULL != mdoc) {
        !          1002:                        if (NULL != (cp = mdoc_meta(mdoc)->name))
        !          1003:                                putkey(of, cp, TYPE_Nm);
        !          1004:                        parse_mdoc(of, mdoc_node(mdoc));
        !          1005:                } else if (NULL != man)
        !          1006:                        parse_man(of, man_node(man));
        !          1007:                else
        !          1008:                        parse_catpage(of, base);
1.44      kristaps 1009:
1.50    ! kristaps 1010:                dbindex(mc, form, of, base);
        !          1011:        }
1.44      kristaps 1012:
1.50    ! kristaps 1013:        return(1);
        !          1014: }
1.12      schwarze 1015:
1.50    ! kristaps 1016: static void
        !          1017: parse_catpage(struct of *of, const char *base)
        !          1018: {
        !          1019:        FILE            *stream;
        !          1020:        char            *line, *p, *title;
        !          1021:        size_t           len, plen, titlesz;
1.12      schwarze 1022:
1.50    ! kristaps 1023:        if (NULL == (stream = fopen(of->file, "r"))) {
        !          1024:                WARNING(of->file, base, "%s", strerror(errno));
        !          1025:                return;
        !          1026:        }
1.1       kristaps 1027:
1.50    ! kristaps 1028:        /* Skip to first blank line. */
1.1       kristaps 1029:
1.50    ! kristaps 1030:        while (NULL != (line = fgetln(stream, &len)))
        !          1031:                if ('\n' == *line)
        !          1032:                        break;
1.1       kristaps 1033:
1.50    ! kristaps 1034:        /*
        !          1035:         * Assume the first line that is not indented
        !          1036:         * is the first section header.  Skip to it.
        !          1037:         */
1.1       kristaps 1038:
1.50    ! kristaps 1039:        while (NULL != (line = fgetln(stream, &len)))
        !          1040:                if ('\n' != *line && ' ' != *line)
        !          1041:                        break;
        !          1042:
        !          1043:        /*
        !          1044:         * Read up until the next section into a buffer.
        !          1045:         * Strip the leading and trailing newline from each read line,
        !          1046:         * appending a trailing space.
        !          1047:         * Ignore empty (whitespace-only) lines.
        !          1048:         */
1.1       kristaps 1049:
1.50    ! kristaps 1050:        titlesz = 0;
        !          1051:        title = NULL;
1.38      schwarze 1052:
1.50    ! kristaps 1053:        while (NULL != (line = fgetln(stream, &len))) {
        !          1054:                if (' ' != *line || '\n' != line[len - 1])
        !          1055:                        break;
        !          1056:                while (len > 0 && isspace((unsigned char)*line)) {
        !          1057:                        line++;
        !          1058:                        len--;
        !          1059:                }
        !          1060:                if (1 == len)
1.38      schwarze 1061:                        continue;
1.50    ! kristaps 1062:                title = mandoc_realloc(title, titlesz + len);
        !          1063:                memcpy(title + titlesz, line, len);
        !          1064:                titlesz += len;
        !          1065:                title[titlesz - 1] = ' ';
        !          1066:        }
1.38      schwarze 1067:
1.50    ! kristaps 1068:        /*
        !          1069:         * If no page content can be found, or the input line
        !          1070:         * is already the next section header, or there is no
        !          1071:         * trailing newline, reuse the page title as the page
        !          1072:         * description.
        !          1073:         */
1.44      kristaps 1074:
1.50    ! kristaps 1075:        if (NULL == title || '\0' == *title) {
        !          1076:                WARNING(of->file, base, "Cannot find NAME section");
        !          1077:                fclose(stream);
        !          1078:                free(title);
        !          1079:                return;
        !          1080:        }
1.1       kristaps 1081:
1.50    ! kristaps 1082:        title = mandoc_realloc(title, titlesz + 1);
        !          1083:        title[titlesz] = '\0';
1.33      schwarze 1084:
1.50    ! kristaps 1085:        /*
        !          1086:         * Skip to the first dash.
        !          1087:         * Use the remaining line as the description (no more than 70
        !          1088:         * bytes).
        !          1089:         */
1.33      schwarze 1090:
1.50    ! kristaps 1091:        if (NULL != (p = strstr(title, "- "))) {
        !          1092:                for (p += 2; ' ' == *p || '\b' == *p; p++)
        !          1093:                        /* Skip to next word. */ ;
        !          1094:        } else {
        !          1095:                WARNING(of->file, base, "No dash in title line");
        !          1096:                p = title;
        !          1097:        }
1.38      schwarze 1098:
1.50    ! kristaps 1099:        plen = strlen(p);
1.1       kristaps 1100:
1.50    ! kristaps 1101:        /* Strip backspace-encoding from line. */
1.1       kristaps 1102:
1.50    ! kristaps 1103:        while (NULL != (line = memchr(p, '\b', plen))) {
        !          1104:                len = line - p;
        !          1105:                if (0 == len) {
        !          1106:                        memmove(line, line + 1, plen--);
        !          1107:                        continue;
        !          1108:                }
        !          1109:                memmove(line - 1, line + 1, plen - len);
        !          1110:                plen -= 2;
        !          1111:        }
1.1       kristaps 1112:
1.50    ! kristaps 1113:        of->desc = stradd(p);
        !          1114:        putkey(of, p, TYPE_Nd);
        !          1115:        fclose(stream);
        !          1116:        free(title);
        !          1117: }
1.1       kristaps 1118:
1.50    ! kristaps 1119: /*
        !          1120:  * Put a type/word pair into the word database for this particular file.
        !          1121:  */
        !          1122: static void
        !          1123: putkey(const struct of *of, const char *value, uint64_t type)
        !          1124: {
1.18      kristaps 1125:
1.50    ! kristaps 1126:        assert(NULL != value);
        !          1127:        wordaddbuf(of, value, strlen(value), type);
        !          1128: }
1.44      kristaps 1129:
1.50    ! kristaps 1130: /*
        !          1131:  * Like putkey() but for unterminated strings.
        !          1132:  */
        !          1133: static void
        !          1134: putkeys(const struct of *of, const char *value, int sz, uint64_t type)
        !          1135: {
1.44      kristaps 1136:
1.50    ! kristaps 1137:        wordaddbuf(of, value, sz, type);
1.3       kristaps 1138: }
                   1139:
                   1140: /*
1.50    ! kristaps 1141:  * Grok all nodes at or below a certain mdoc node into putkey().
1.3       kristaps 1142:  */
                   1143: static void
1.50    ! kristaps 1144: putmdockey(const struct of *of, const struct mdoc_node *n, uint64_t m)
1.3       kristaps 1145: {
1.18      kristaps 1146:
1.50    ! kristaps 1147:        for ( ; NULL != n; n = n->next) {
        !          1148:                if (NULL != n->child)
        !          1149:                        putmdockey(of, n->child, m);
        !          1150:                if (MDOC_TEXT == n->type)
        !          1151:                        putkey(of, n->string, m);
        !          1152:        }
        !          1153: }
1.18      kristaps 1154:
1.50    ! kristaps 1155: static int
        !          1156: parse_man(struct of *of, const struct man_node *n)
        !          1157: {
        !          1158:        const struct man_node *head, *body;
        !          1159:        char            *start, *sv, *title;
        !          1160:        char             byte;
        !          1161:        size_t           sz, titlesz;
1.18      kristaps 1162:
1.50    ! kristaps 1163:        if (NULL == n)
        !          1164:                return(0);
1.18      kristaps 1165:
1.50    ! kristaps 1166:        /*
        !          1167:         * We're only searching for one thing: the first text child in
        !          1168:         * the BODY of a NAME section.  Since we don't keep track of
        !          1169:         * sections in -man, run some hoops to find out whether we're in
        !          1170:         * the correct section or not.
        !          1171:         */
1.18      kristaps 1172:
1.50    ! kristaps 1173:        if (MAN_BODY == n->type && MAN_SH == n->tok) {
        !          1174:                body = n;
        !          1175:                assert(body->parent);
        !          1176:                if (NULL != (head = body->parent->head) &&
        !          1177:                                1 == head->nchild &&
        !          1178:                                NULL != (head = (head->child)) &&
        !          1179:                                MAN_TEXT == head->type &&
        !          1180:                                0 == strcmp(head->string, "NAME") &&
        !          1181:                                NULL != (body = body->child) &&
        !          1182:                                MAN_TEXT == body->type) {
1.3       kristaps 1183:
1.50    ! kristaps 1184:                        title = NULL;
        !          1185:                        titlesz = 0;
1.3       kristaps 1186:
1.50    ! kristaps 1187:                        /*
        !          1188:                         * Suck the entire NAME section into memory.
        !          1189:                         * Yes, we might run away.
        !          1190:                         * But too many manuals have big, spread-out
        !          1191:                         * NAME sections over many lines.
        !          1192:                         */
1.3       kristaps 1193:
1.50    ! kristaps 1194:                        for ( ; NULL != body; body = body->next) {
        !          1195:                                if (MAN_TEXT != body->type)
        !          1196:                                        break;
        !          1197:                                if (0 == (sz = strlen(body->string)))
        !          1198:                                        continue;
        !          1199:                                title = mandoc_realloc
        !          1200:                                        (title, titlesz + sz + 1);
        !          1201:                                memcpy(title + titlesz, body->string, sz);
        !          1202:                                titlesz += sz + 1;
        !          1203:                                title[titlesz - 1] = ' ';
        !          1204:                        }
        !          1205:                        if (NULL == title)
        !          1206:                                return(1);
1.18      kristaps 1207:
1.50    ! kristaps 1208:                        title = mandoc_realloc(title, titlesz + 1);
        !          1209:                        title[titlesz] = '\0';
1.18      kristaps 1210:
1.50    ! kristaps 1211:                        /* Skip leading space.  */
1.18      kristaps 1212:
1.50    ! kristaps 1213:                        sv = title;
        !          1214:                        while (isspace((unsigned char)*sv))
        !          1215:                                sv++;
1.18      kristaps 1216:
1.50    ! kristaps 1217:                        if (0 == (sz = strlen(sv))) {
        !          1218:                                free(title);
        !          1219:                                return(1);
        !          1220:                        }
1.1       kristaps 1221:
1.50    ! kristaps 1222:                        /* Erase trailing space. */
1.1       kristaps 1223:
1.50    ! kristaps 1224:                        start = &sv[sz - 1];
        !          1225:                        while (start > sv && isspace((unsigned char)*start))
        !          1226:                                *start-- = '\0';
1.1       kristaps 1227:
1.50    ! kristaps 1228:                        if (start == sv) {
        !          1229:                                free(title);
        !          1230:                                return(1);
        !          1231:                        }
1.1       kristaps 1232:
1.50    ! kristaps 1233:                        start = sv;
1.18      kristaps 1234:
1.50    ! kristaps 1235:                        /*
        !          1236:                         * Go through a special heuristic dance here.
        !          1237:                         * Conventionally, one or more manual names are
        !          1238:                         * comma-specified prior to a whitespace, then a
        !          1239:                         * dash, then a description.  Try to puzzle out
        !          1240:                         * the name parts here.
        !          1241:                         */
1.18      kristaps 1242:
1.50    ! kristaps 1243:                        for ( ;; ) {
        !          1244:                                sz = strcspn(start, " ,");
        !          1245:                                if ('\0' == start[sz])
        !          1246:                                        break;
1.1       kristaps 1247:
1.50    ! kristaps 1248:                                byte = start[sz];
        !          1249:                                start[sz] = '\0';
1.1       kristaps 1250:
1.50    ! kristaps 1251:                                putkey(of, start, TYPE_Nm);
1.1       kristaps 1252:
1.50    ! kristaps 1253:                                if (' ' == byte) {
        !          1254:                                        start += sz + 1;
        !          1255:                                        break;
        !          1256:                                }
1.1       kristaps 1257:
1.50    ! kristaps 1258:                                assert(',' == byte);
        !          1259:                                start += sz + 1;
        !          1260:                                while (' ' == *start)
        !          1261:                                        start++;
        !          1262:                        }
1.1       kristaps 1263:
1.50    ! kristaps 1264:                        if (sv == start) {
        !          1265:                                putkey(of, start, TYPE_Nm);
        !          1266:                                free(title);
        !          1267:                                return(1);
        !          1268:                        }
1.1       kristaps 1269:
1.50    ! kristaps 1270:                        while (isspace((unsigned char)*start))
        !          1271:                                start++;
1.1       kristaps 1272:
1.50    ! kristaps 1273:                        if (0 == strncmp(start, "-", 1))
        !          1274:                                start += 1;
        !          1275:                        else if (0 == strncmp(start, "\\-\\-", 4))
        !          1276:                                start += 4;
        !          1277:                        else if (0 == strncmp(start, "\\-", 2))
        !          1278:                                start += 2;
        !          1279:                        else if (0 == strncmp(start, "\\(en", 4))
        !          1280:                                start += 4;
        !          1281:                        else if (0 == strncmp(start, "\\(em", 4))
        !          1282:                                start += 4;
1.1       kristaps 1283:
1.50    ! kristaps 1284:                        while (' ' == *start)
        !          1285:                                start++;
1.1       kristaps 1286:
1.50    ! kristaps 1287:                        assert(NULL == of->desc);
        !          1288:                        of->desc = stradd(start);
        !          1289:                        putkey(of, start, TYPE_Nd);
        !          1290:                        free(title);
        !          1291:                        return(1);
        !          1292:                }
        !          1293:        }
1.1       kristaps 1294:
1.50    ! kristaps 1295:        for (n = n->child; n; n = n->next)
        !          1296:                if (parse_man(of, n))
        !          1297:                        return(1);
1.1       kristaps 1298:
1.50    ! kristaps 1299:        return(0);
1.1       kristaps 1300: }
                   1301:
                   1302: static void
1.50    ! kristaps 1303: parse_mdoc(struct of *of, const struct mdoc_node *n)
1.1       kristaps 1304: {
                   1305:
1.50    ! kristaps 1306:        assert(NULL != n);
        !          1307:        for (n = n->child; NULL != n; n = n->next) {
        !          1308:                switch (n->type) {
        !          1309:                case (MDOC_ELEM):
        !          1310:                        /* FALLTHROUGH */
        !          1311:                case (MDOC_BLOCK):
        !          1312:                        /* FALLTHROUGH */
        !          1313:                case (MDOC_HEAD):
        !          1314:                        /* FALLTHROUGH */
        !          1315:                case (MDOC_BODY):
        !          1316:                        /* FALLTHROUGH */
        !          1317:                case (MDOC_TAIL):
        !          1318:                        if (NULL != mdocs[n->tok].fp)
        !          1319:                               if (0 == (*mdocs[n->tok].fp)(of, n))
        !          1320:                                       break;
1.1       kristaps 1321:
1.50    ! kristaps 1322:                        if (MDOCF_CHILD & mdocs[n->tok].flags)
        !          1323:                                putmdockey(of, n->child, mdocs[n->tok].mask);
        !          1324:                        break;
        !          1325:                default:
        !          1326:                        assert(MDOC_ROOT != n->type);
        !          1327:                        continue;
        !          1328:                }
        !          1329:                if (NULL != n->child)
        !          1330:                        parse_mdoc(of, n);
1.1       kristaps 1331:        }
                   1332: }
                   1333:
1.25      schwarze 1334: static int
1.50    ! kristaps 1335: parse_mdoc_Fd(struct of *of, const struct mdoc_node *n)
1.1       kristaps 1336: {
                   1337:        const char      *start, *end;
                   1338:        size_t           sz;
1.25      schwarze 1339:
1.50    ! kristaps 1340:        if (SEC_SYNOPSIS != n->sec ||
        !          1341:                        NULL == (n = n->child) ||
        !          1342:                        MDOC_TEXT != n->type)
1.25      schwarze 1343:                return(0);
1.1       kristaps 1344:
                   1345:        /*
                   1346:         * Only consider those `Fd' macro fields that begin with an
                   1347:         * "inclusion" token (versus, e.g., #define).
                   1348:         */
1.50    ! kristaps 1349:
1.1       kristaps 1350:        if (strcmp("#include", n->string))
1.25      schwarze 1351:                return(0);
1.1       kristaps 1352:
                   1353:        if (NULL == (n = n->next) || MDOC_TEXT != n->type)
1.25      schwarze 1354:                return(0);
1.1       kristaps 1355:
                   1356:        /*
                   1357:         * Strip away the enclosing angle brackets and make sure we're
                   1358:         * not zero-length.
                   1359:         */
                   1360:
                   1361:        start = n->string;
                   1362:        if ('<' == *start || '"' == *start)
                   1363:                start++;
                   1364:
                   1365:        if (0 == (sz = strlen(start)))
1.25      schwarze 1366:                return(0);
1.1       kristaps 1367:
                   1368:        end = &start[(int)sz - 1];
                   1369:        if ('>' == *end || '"' == *end)
                   1370:                end--;
                   1371:
1.50    ! kristaps 1372:        if (end > start)
        !          1373:                putkeys(of, start, end - start + 1, TYPE_In);
1.25      schwarze 1374:        return(1);
1.1       kristaps 1375: }
                   1376:
1.25      schwarze 1377: static int
1.50    ! kristaps 1378: parse_mdoc_In(struct of *of, const struct mdoc_node *n)
1.1       kristaps 1379: {
                   1380:
1.50    ! kristaps 1381:        if (NULL != n->child && MDOC_TEXT == n->child->type)
1.25      schwarze 1382:                return(0);
1.1       kristaps 1383:
1.50    ! kristaps 1384:        putkey(of, n->child->string, TYPE_In);
1.25      schwarze 1385:        return(1);
1.1       kristaps 1386: }
                   1387:
1.25      schwarze 1388: static int
1.50    ! kristaps 1389: parse_mdoc_Fn(struct of *of, const struct mdoc_node *n)
1.1       kristaps 1390: {
                   1391:        const char      *cp;
                   1392:
1.50    ! kristaps 1393:        if (NULL == (n = n->child) || MDOC_TEXT != n->type)
1.25      schwarze 1394:                return(0);
                   1395:
1.50    ! kristaps 1396:        /*
        !          1397:         * Parse: .Fn "struct type *name" "char *arg".
        !          1398:         * First strip away pointer symbol.
        !          1399:         * Then store the function name, then type.
        !          1400:         * Finally, store the arguments.
        !          1401:         */
1.1       kristaps 1402:
1.50    ! kristaps 1403:        if (NULL == (cp = strrchr(n->string, ' ')))
        !          1404:                cp = n->string;
1.1       kristaps 1405:
                   1406:        while ('*' == *cp)
                   1407:                cp++;
                   1408:
1.50    ! kristaps 1409:        putkey(of, cp, TYPE_Fn);
1.25      schwarze 1410:
1.50    ! kristaps 1411:        if (n->string < cp)
        !          1412:                putkeys(of, n->string, cp - n->string, TYPE_Ft);
1.25      schwarze 1413:
1.50    ! kristaps 1414:        for (n = n->next; NULL != n; n = n->next)
        !          1415:                if (MDOC_TEXT == n->type)
        !          1416:                        putkey(of, n->string, TYPE_Fa);
1.25      schwarze 1417:
                   1418:        return(0);
1.1       kristaps 1419: }
                   1420:
1.25      schwarze 1421: static int
1.50    ! kristaps 1422: parse_mdoc_St(struct of *of, const struct mdoc_node *n)
1.1       kristaps 1423: {
1.25      schwarze 1424:
1.1       kristaps 1425:        if (NULL == n->child || MDOC_TEXT != n->child->type)
1.25      schwarze 1426:                return(0);
1.1       kristaps 1427:
1.50    ! kristaps 1428:        putkey(of, n->child->string, TYPE_St);
1.25      schwarze 1429:        return(1);
1.1       kristaps 1430: }
                   1431:
1.25      schwarze 1432: static int
1.50    ! kristaps 1433: parse_mdoc_Xr(struct of *of, const struct mdoc_node *n)
1.1       kristaps 1434: {
                   1435:
                   1436:        if (NULL == (n = n->child))
1.25      schwarze 1437:                return(0);
1.1       kristaps 1438:
1.50    ! kristaps 1439:        putkey(of, n->string, TYPE_Xr);
1.25      schwarze 1440:        return(1);
1.1       kristaps 1441: }
                   1442:
1.25      schwarze 1443: static int
1.50    ! kristaps 1444: parse_mdoc_Nd(struct of *of, const struct mdoc_node *n)
1.1       kristaps 1445: {
1.50    ! kristaps 1446:        size_t           sz;
        !          1447:        char            *sv, *desc;
1.1       kristaps 1448:
                   1449:        if (MDOC_BODY != n->type)
1.25      schwarze 1450:                return(0);
1.1       kristaps 1451:
1.50    ! kristaps 1452:        /*
        !          1453:         * Special-case the `Nd' because we need to put the description
        !          1454:         * into the document table.
        !          1455:         */
        !          1456:
        !          1457:        desc = NULL;
        !          1458:        for (n = n->child; NULL != n; n = n->next) {
        !          1459:                if (MDOC_TEXT == n->type) {
        !          1460:                        sz = strlen(n->string) + 1;
        !          1461:                        if (NULL != (sv = desc))
        !          1462:                                sz += strlen(desc) + 1;
        !          1463:                        desc = mandoc_realloc(desc, sz);
        !          1464:                        if (NULL != sv)
        !          1465:                                strlcat(desc, " ", sz);
        !          1466:                        else
        !          1467:                                *desc = '\0';
        !          1468:                        strlcat(desc, n->string, sz);
        !          1469:                }
        !          1470:                if (NULL != n->child)
        !          1471:                        parse_mdoc_Nd(of, n);
        !          1472:        }
        !          1473:
        !          1474:        of->desc = NULL != desc ? stradd(desc) : NULL;
        !          1475:        free(desc);
1.25      schwarze 1476:        return(1);
1.1       kristaps 1477: }
                   1478:
1.25      schwarze 1479: static int
1.50    ! kristaps 1480: parse_mdoc_Nm(struct of *of, const struct mdoc_node *n)
1.1       kristaps 1481: {
                   1482:
1.25      schwarze 1483:        if (SEC_NAME == n->sec)
                   1484:                return(1);
                   1485:        else if (SEC_SYNOPSIS != n->sec || MDOC_HEAD != n->type)
                   1486:                return(0);
1.1       kristaps 1487:
1.25      schwarze 1488:        return(1);
1.1       kristaps 1489: }
                   1490:
1.25      schwarze 1491: static int
1.50    ! kristaps 1492: parse_mdoc_Sh(struct of *of, const struct mdoc_node *n)
1.1       kristaps 1493: {
                   1494:
1.25      schwarze 1495:        return(SEC_CUSTOM == n->sec && MDOC_HEAD == n->type);
1.1       kristaps 1496: }
                   1497:
1.50    ! kristaps 1498: static int
        !          1499: parse_mdoc_head(struct of *of, const struct mdoc_node *n)
1.1       kristaps 1500: {
                   1501:
1.50    ! kristaps 1502:        return(MDOC_HEAD == n->type);
        !          1503: }
1.1       kristaps 1504:
1.50    ! kristaps 1505: static int
        !          1506: parse_mdoc_body(struct of *of, const struct mdoc_node *n)
        !          1507: {
1.1       kristaps 1508:
1.50    ! kristaps 1509:        return(MDOC_BODY == n->type);
1.1       kristaps 1510: }
                   1511:
1.50    ! kristaps 1512: /*
        !          1513:  * See straddbuf().
        !          1514:  */
        !          1515: static char *
        !          1516: stradd(const char *cp)
1.1       kristaps 1517: {
                   1518:
1.50    ! kristaps 1519:        return(straddbuf(cp, strlen(cp)));
1.1       kristaps 1520: }
                   1521:
                   1522: /*
1.50    ! kristaps 1523:  * This looks up or adds a string to the string table.
        !          1524:  * The string table is a table of all strings encountered during parse
        !          1525:  * or file scan.
        !          1526:  * In using it, we avoid having thousands of (e.g.) "cat1" string
        !          1527:  * allocations for the "of" table.
        !          1528:  * We also have a layer atop the string table for keeping track of words
        !          1529:  * in a parse sequence (see wordaddbuf()).
1.1       kristaps 1530:  */
1.50    ! kristaps 1531: static char *
        !          1532: straddbuf(const char *cp, size_t sz)
1.1       kristaps 1533: {
1.50    ! kristaps 1534:        struct str      *s;
        !          1535:        unsigned int     index;
        !          1536:        const char      *end;
        !          1537:
        !          1538:        if (NULL != (s = hashget(cp, sz)))
        !          1539:                return(s->key);
1.1       kristaps 1540:
1.50    ! kristaps 1541:        s = mandoc_calloc(sizeof(struct str) + sz, 1);
        !          1542:        memcpy(s->key, cp, sz);
1.1       kristaps 1543:
1.50    ! kristaps 1544:        end = cp + sz;
        !          1545:        index = ohash_qlookupi(&strings, cp, &end);
        !          1546:        assert(NULL == ohash_find(&strings, index));
        !          1547:        ohash_insert(&strings, index, s);
        !          1548:        return(s->key);
        !          1549: }
1.25      schwarze 1550:
1.50    ! kristaps 1551: static struct str *
        !          1552: hashget(const char *cp, size_t sz)
        !          1553: {
        !          1554:        unsigned int     index;
        !          1555:        const char      *end;
1.25      schwarze 1556:
1.50    ! kristaps 1557:        end = cp + sz;
        !          1558:        index = ohash_qlookupi(&strings, cp, &end);
        !          1559:        return(ohash_find(&strings, index));
        !          1560: }
1.1       kristaps 1561:
1.50    ! kristaps 1562: /*
        !          1563:  * Add a word to the current parse sequence.
        !          1564:  * Within the hashtable of strings, we maintain a list of strings that
        !          1565:  * are currently indexed.
        !          1566:  * Each of these ("words") has a bitmask modified within the parse.
        !          1567:  * When we finish a parse, we'll dump the list, then remove the head
        !          1568:  * entry -- since the next parse will have a new "of", it can keep track
        !          1569:  * of its entries without conflict.
        !          1570:  */
        !          1571: static void
        !          1572: wordaddbuf(const struct of *of,
        !          1573:                const char *cp, size_t sz, uint64_t v)
        !          1574: {
        !          1575:        struct str      *s;
        !          1576:        unsigned int     index;
        !          1577:        const char      *end;
1.25      schwarze 1578:
1.50    ! kristaps 1579:        if (0 == sz)
        !          1580:                return;
1.25      schwarze 1581:
1.50    ! kristaps 1582:        s = hashget(cp, sz);
1.25      schwarze 1583:
1.50    ! kristaps 1584:        if (NULL != s && of == s->of) {
        !          1585:                s->mask |= v;
        !          1586:                return;
        !          1587:        } else if (NULL == s) {
        !          1588:                s = mandoc_calloc(sizeof(struct str) + sz, 1);
        !          1589:                memcpy(s->key, cp, sz);
        !          1590:                end = cp + sz;
        !          1591:                index = ohash_qlookupi(&strings, cp, &end);
        !          1592:                assert(NULL == ohash_find(&strings, index));
        !          1593:                ohash_insert(&strings, index, s);
1.1       kristaps 1594:        }
                   1595:
1.50    ! kristaps 1596:        s->next = words;
        !          1597:        s->of = of;
        !          1598:        s->mask = v;
        !          1599:        words = s;
1.1       kristaps 1600: }
                   1601:
1.50    ! kristaps 1602: /*
        !          1603:  * Take a Unicode codepoint and produce its UTF-8 encoding.
        !          1604:  * This isn't the best way to do this, but it works.
        !          1605:  * The magic numbers are from the UTF-8 packaging.
        !          1606:  * They're not as scary as they seem: read the UTF-8 spec for details.
        !          1607:  */
        !          1608: static size_t
        !          1609: utf8(unsigned int cp, char out[7])
1.1       kristaps 1610: {
1.50    ! kristaps 1611:        size_t           rc;
1.1       kristaps 1612:
1.50    ! kristaps 1613:        rc = 0;
        !          1614:        if (cp <= 0x0000007F) {
        !          1615:                rc = 1;
        !          1616:                out[0] = (char)cp;
        !          1617:        } else if (cp <= 0x000007FF) {
        !          1618:                rc = 2;
        !          1619:                out[0] = (cp >> 6  & 31) | 192;
        !          1620:                out[1] = (cp       & 63) | 128;
        !          1621:        } else if (cp <= 0x0000FFFF) {
        !          1622:                rc = 3;
        !          1623:                out[0] = (cp >> 12 & 15) | 224;
        !          1624:                out[1] = (cp >> 6  & 63) | 128;
        !          1625:                out[2] = (cp       & 63) | 128;
        !          1626:        } else if (cp <= 0x001FFFFF) {
        !          1627:                rc = 4;
        !          1628:                out[0] = (cp >> 18 &  7) | 240;
        !          1629:                out[1] = (cp >> 12 & 63) | 128;
        !          1630:                out[2] = (cp >> 6  & 63) | 128;
        !          1631:                out[3] = (cp       & 63) | 128;
        !          1632:        } else if (cp <= 0x03FFFFFF) {
        !          1633:                rc = 5;
        !          1634:                out[0] = (cp >> 24 &  3) | 248;
        !          1635:                out[1] = (cp >> 18 & 63) | 128;
        !          1636:                out[2] = (cp >> 12 & 63) | 128;
        !          1637:                out[3] = (cp >> 6  & 63) | 128;
        !          1638:                out[4] = (cp       & 63) | 128;
        !          1639:        } else if (cp <= 0x7FFFFFFF) {
        !          1640:                rc = 6;
        !          1641:                out[0] = (cp >> 30 &  1) | 252;
        !          1642:                out[1] = (cp >> 24 & 63) | 128;
        !          1643:                out[2] = (cp >> 18 & 63) | 128;
        !          1644:                out[3] = (cp >> 12 & 63) | 128;
        !          1645:                out[4] = (cp >> 6  & 63) | 128;
        !          1646:                out[5] = (cp       & 63) | 128;
        !          1647:        } else
1.1       kristaps 1648:                return(0);
                   1649:
1.50    ! kristaps 1650:        out[rc] = '\0';
        !          1651:        return(rc);
        !          1652: }
1.1       kristaps 1653:
1.50    ! kristaps 1654: /*
        !          1655:  * Store the UTF-8 version of a key, or alias the pointer if the key has
        !          1656:  * no UTF-8 transcription marks in it.
        !          1657:  */
        !          1658: static void
        !          1659: utf8key(struct mchars *mc, struct str *key)
        !          1660: {
        !          1661:        size_t           sz, bsz, pos;
        !          1662:        char             utfbuf[7], res[5];
        !          1663:        char            *buf;
        !          1664:        const char      *seq, *cpp, *val;
        !          1665:        int              len, u;
        !          1666:        enum mandoc_esc  esc;
        !          1667:
        !          1668:        assert(NULL == key->utf8);
        !          1669:
        !          1670:        res[0] = '\\';
        !          1671:        res[1] = '\t';
        !          1672:        res[2] = ASCII_NBRSP;
        !          1673:        res[3] = ASCII_HYPH;
        !          1674:        res[4] = '\0';
1.1       kristaps 1675:
1.50    ! kristaps 1676:        val = key->key;
        !          1677:        bsz = strlen(val);
1.46      kristaps 1678:
1.50    ! kristaps 1679:        /*
        !          1680:         * Pre-check: if we have no stop-characters, then set the
        !          1681:         * pointer as ourselvse and get out of here.
        !          1682:         */
        !          1683:        if (strcspn(val, res) == bsz) {
        !          1684:                key->utf8 = key->key;
        !          1685:                return;
        !          1686:        }
1.46      kristaps 1687:
1.50    ! kristaps 1688:        /* Pre-allocate by the length of the input */
1.46      kristaps 1689:
1.50    ! kristaps 1690:        buf = mandoc_malloc(++bsz);
        !          1691:        pos = 0;
1.46      kristaps 1692:
1.50    ! kristaps 1693:        while ('\0' != *val) {
        !          1694:                /*
        !          1695:                 * Halt on the first escape sequence.
        !          1696:                 * This also halts on the end of string, in which case
        !          1697:                 * we just copy, fallthrough, and exit the loop.
        !          1698:                 */
        !          1699:                if ((sz = strcspn(val, res)) > 0) {
        !          1700:                        memcpy(&buf[pos], val, sz);
        !          1701:                        pos += sz;
        !          1702:                        val += sz;
        !          1703:                }
1.46      kristaps 1704:
1.50    ! kristaps 1705:                if (ASCII_HYPH == *val) {
        !          1706:                        buf[pos++] = '-';
        !          1707:                        val++;
        !          1708:                        continue;
        !          1709:                } else if ('\t' == *val || ASCII_NBRSP == *val) {
        !          1710:                        buf[pos++] = ' ';
        !          1711:                        val++;
        !          1712:                        continue;
        !          1713:                } else if ('\\' != *val)
        !          1714:                        break;
1.46      kristaps 1715:
1.50    ! kristaps 1716:                /* Read past the slash. */
1.46      kristaps 1717:
1.50    ! kristaps 1718:                val++;
        !          1719:                u = 0;
1.46      kristaps 1720:
1.50    ! kristaps 1721:                /*
        !          1722:                 * Parse the escape sequence and see if it's a
        !          1723:                 * predefined character or special character.
        !          1724:                 */
        !          1725:                esc = mandoc_escape
        !          1726:                        ((const char **)&val, &seq, &len);
        !          1727:                if (ESCAPE_ERROR == esc)
        !          1728:                        break;
1.1       kristaps 1729:
1.50    ! kristaps 1730:                if (ESCAPE_SPECIAL != esc)
        !          1731:                        continue;
        !          1732:                if (0 == (u = mchars_spec2cp(mc, seq, len)))
        !          1733:                        continue;
1.1       kristaps 1734:
1.50    ! kristaps 1735:                /*
        !          1736:                 * If we have a Unicode codepoint, try to convert that
        !          1737:                 * to a UTF-8 byte string.
        !          1738:                 */
        !          1739:                cpp = utfbuf;
        !          1740:                if (0 == (sz = utf8(u, utfbuf)))
        !          1741:                        continue;
1.1       kristaps 1742:
1.50    ! kristaps 1743:                /* Copy the rendered glyph into the stream. */
1.1       kristaps 1744:
1.50    ! kristaps 1745:                sz = strlen(cpp);
        !          1746:                bsz += sz;
1.1       kristaps 1747:
1.50    ! kristaps 1748:                buf = mandoc_realloc(buf, bsz);
1.1       kristaps 1749:
1.50    ! kristaps 1750:                memcpy(&buf[pos], cpp, sz);
        !          1751:                pos += sz;
1.1       kristaps 1752:        }
                   1753:
1.50    ! kristaps 1754:        buf[pos] = '\0';
        !          1755:        key->utf8 = buf;
1.1       kristaps 1756: }
                   1757:
1.14      schwarze 1758: /*
1.50    ! kristaps 1759:  * Flush the current page's terms (and their bits) into the database.
        !          1760:  * Wrap the entire set of additions in a transaction to make sqlite be a
        !          1761:  * little faster.
        !          1762:  * Also, UTF-8-encode the description at the last possible moment.
1.14      schwarze 1763:  */
                   1764: static void
1.50    ! kristaps 1765: dbindex(struct mchars *mc, int form,
        !          1766:                const struct of *of, const char *base)
1.14      schwarze 1767: {
1.50    ! kristaps 1768:        struct str      *key;
        !          1769:        const char      *desc;
        !          1770:        int64_t          recno;
1.14      schwarze 1771:
1.50    ! kristaps 1772:        DEBUG(of->file, base, "Adding to index");
1.43      kristaps 1773:
1.50    ! kristaps 1774:        if (nodb)
1.14      schwarze 1775:                return;
1.28      kristaps 1776:
1.50    ! kristaps 1777:        desc = "";
        !          1778:        if (NULL != of->desc) {
        !          1779:                key = hashget(of->desc, strlen(of->desc));
        !          1780:                assert(NULL != key);
        !          1781:                if (NULL == key->utf8)
        !          1782:                        utf8key(mc, key);
        !          1783:                desc = key->utf8;
        !          1784:        }
        !          1785:
        !          1786:        sqlite3_exec(db, "BEGIN TRANSACTION", NULL, NULL, NULL);
        !          1787:
        !          1788:        sqlite3_bind_text
        !          1789:                (stmts[STMT_INSERT_DOC], 1,
        !          1790:                 of->file, -1, SQLITE_STATIC);
        !          1791:        sqlite3_bind_text
        !          1792:                (stmts[STMT_INSERT_DOC], 2,
        !          1793:                 of->sec, -1, SQLITE_STATIC);
        !          1794:        sqlite3_bind_text
        !          1795:                (stmts[STMT_INSERT_DOC], 3,
        !          1796:                 of->arch, -1, SQLITE_STATIC);
        !          1797:        sqlite3_bind_text
        !          1798:                (stmts[STMT_INSERT_DOC], 4,
        !          1799:                 desc, -1, SQLITE_STATIC);
        !          1800:        sqlite3_bind_int
        !          1801:                (stmts[STMT_INSERT_DOC], 5, form);
        !          1802:        sqlite3_step(stmts[STMT_INSERT_DOC]);
        !          1803:        recno = sqlite3_last_insert_rowid(db);
        !          1804:        sqlite3_reset(stmts[STMT_INSERT_DOC]);
        !          1805:
        !          1806:        for (key = words; NULL != key; key = key->next) {
        !          1807:                assert(key->of == of);
        !          1808:                if (NULL == key->utf8)
        !          1809:                        utf8key(mc, key);
        !          1810:                sqlite3_bind_int64
        !          1811:                        (stmts[STMT_INSERT_KEY], 1, key->mask);
        !          1812:                sqlite3_bind_text
        !          1813:                        (stmts[STMT_INSERT_KEY], 2,
        !          1814:                         key->utf8, -1, SQLITE_STATIC);
        !          1815:                sqlite3_bind_int64
        !          1816:                        (stmts[STMT_INSERT_KEY], 3, recno);
        !          1817:                sqlite3_step(stmts[STMT_INSERT_KEY]);
        !          1818:                sqlite3_reset(stmts[STMT_INSERT_KEY]);
1.38      schwarze 1819:        }
1.28      kristaps 1820:
1.50    ! kristaps 1821:        sqlite3_exec(db, "COMMIT TRANSACTION", NULL, NULL, NULL);
1.14      schwarze 1822:
                   1823: }
                   1824:
1.5       kristaps 1825: static void
1.50    ! kristaps 1826: dbprune(const char *base)
1.5       kristaps 1827: {
1.50    ! kristaps 1828:        struct of       *of;
1.5       kristaps 1829:
1.50    ! kristaps 1830:        if (nodb)
        !          1831:                return;
1.12      schwarze 1832:
1.50    ! kristaps 1833:        for (of = ofs; NULL != of; of = of->next) {
        !          1834:                sqlite3_bind_text
        !          1835:                        (stmts[STMT_DELETE], 1,
        !          1836:                         of->file, -1, SQLITE_STATIC);
        !          1837:                sqlite3_step(stmts[STMT_DELETE]);
        !          1838:                sqlite3_reset(stmts[STMT_DELETE]);
        !          1839:                DEBUG(of->file, base, "Deleted from index");
1.5       kristaps 1840:        }
                   1841: }
                   1842:
1.4       kristaps 1843: /*
1.50    ! kristaps 1844:  * Close an existing database and its prepared statements.
        !          1845:  * If "real" is not set, rename the temporary file into the real one.
1.4       kristaps 1846:  */
1.35      kristaps 1847: static void
1.50    ! kristaps 1848: dbclose(const char *base, int real)
1.4       kristaps 1849: {
1.50    ! kristaps 1850:        size_t           i;
        !          1851:        char             file[MAXPATHLEN];
1.4       kristaps 1852:
1.50    ! kristaps 1853:        if (nodb)
1.38      schwarze 1854:                return;
1.50    ! kristaps 1855:
        !          1856:        for (i = 0; i < STMT__MAX; i++) {
        !          1857:                sqlite3_finalize(stmts[i]);
        !          1858:                stmts[i] = NULL;
1.4       kristaps 1859:        }
                   1860:
1.50    ! kristaps 1861:        sqlite3_close(db);
        !          1862:        db = NULL;
1.12      schwarze 1863:
1.50    ! kristaps 1864:        if (real)
        !          1865:                return;
1.12      schwarze 1866:
1.50    ! kristaps 1867:        strlcpy(file, MANDOC_DB, MAXPATHLEN);
        !          1868:        strlcat(file, "~", MAXPATHLEN);
        !          1869:        if (-1 == rename(file, MANDOC_DB))
        !          1870:                perror(MANDOC_DB);
        !          1871: }
1.14      schwarze 1872:
1.50    ! kristaps 1873: /*
        !          1874:  * This is straightforward stuff.
        !          1875:  * Open a database connection to a "temporary" database, then open a set
        !          1876:  * of prepared statements we'll use over and over again.
        !          1877:  * If "real" is set, we use the existing database; if not, we truncate a
        !          1878:  * temporary one.
        !          1879:  * Must be matched by dbclose().
        !          1880:  */
        !          1881: static int
        !          1882: dbopen(const char *base, int real)
        !          1883: {
        !          1884:        char             file[MAXPATHLEN];
        !          1885:        const char      *sql;
        !          1886:        int              rc, ofl;
        !          1887:        size_t           sz;
1.12      schwarze 1888:
1.50    ! kristaps 1889:        if (nodb)
        !          1890:                return(1);
1.12      schwarze 1891:
1.50    ! kristaps 1892:        sz = strlcpy(file, MANDOC_DB, MAXPATHLEN);
        !          1893:        if ( ! real)
        !          1894:                sz = strlcat(file, "~", MAXPATHLEN);
1.5       kristaps 1895:
1.50    ! kristaps 1896:        if (sz >= MAXPATHLEN) {
        !          1897:                fprintf(stderr, "%s: Path too long\n", file);
        !          1898:                return(0);
        !          1899:        }
1.5       kristaps 1900:
1.50    ! kristaps 1901:        if ( ! real)
        !          1902:                remove(file);
1.38      schwarze 1903:
1.50    ! kristaps 1904:        ofl = SQLITE_OPEN_PRIVATECACHE | SQLITE_OPEN_READWRITE |
        !          1905:                (0 == real ? SQLITE_OPEN_EXCLUSIVE : 0);
1.45      kristaps 1906:
1.50    ! kristaps 1907:        rc = sqlite3_open_v2(file, &db, ofl, NULL);
        !          1908:        if (SQLITE_OK == rc)
        !          1909:                return(1);
        !          1910:        if (SQLITE_CANTOPEN != rc) {
        !          1911:                perror(file);
        !          1912:                return(0);
        !          1913:        }
1.12      schwarze 1914:
1.50    ! kristaps 1915:        sqlite3_close(db);
        !          1916:        db = NULL;
1.12      schwarze 1917:
1.50    ! kristaps 1918:        if (SQLITE_OK != (rc = sqlite3_open(file, &db))) {
        !          1919:                perror(file);
        !          1920:                return(0);
        !          1921:        }
1.12      schwarze 1922:
1.50    ! kristaps 1923:        sql = "CREATE TABLE \"docs\" (\n"
        !          1924:              " \"file\" TEXT NOT NULL,\n"
        !          1925:              " \"sec\" TEXT NOT NULL,\n"
        !          1926:              " \"arch\" TEXT NOT NULL,\n"
        !          1927:              " \"desc\" TEXT NOT NULL,\n"
        !          1928:              " \"form\" INTEGER NOT NULL,\n"
        !          1929:              " \"id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL\n"
        !          1930:              ");\n"
        !          1931:              "\n"
        !          1932:              "CREATE TABLE \"keys\" (\n"
        !          1933:              " \"bits\" INTEGER NOT NULL,\n"
        !          1934:              " \"key\" TEXT NOT NULL,\n"
        !          1935:              " \"docid\" INTEGER NOT NULL REFERENCES docs(id) "
        !          1936:                "ON DELETE CASCADE,\n"
        !          1937:              " \"id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL\n"
        !          1938:              ");\n"
        !          1939:              "\n"
        !          1940:              "CREATE INDEX \"key_index\" ON keys (key);\n";
1.14      schwarze 1941:
1.50    ! kristaps 1942:        if (SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, NULL)) {
        !          1943:                perror(sqlite3_errmsg(db));
        !          1944:                return(0);
        !          1945:        }
1.4       kristaps 1946:
1.50    ! kristaps 1947:        sql = "DELETE FROM docs where file=?";
        !          1948:        sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_DELETE], NULL);
        !          1949:        sql = "INSERT INTO docs "
        !          1950:                "(file,sec,arch,desc,form) VALUES (?,?,?,?,?)";
        !          1951:        sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_INSERT_DOC], NULL);
        !          1952:        sql = "INSERT INTO keys "
        !          1953:                "(bits,key,docid) VALUES (?,?,?)";
        !          1954:        sqlite3_prepare_v2(db, sql, -1, &stmts[STMT_INSERT_KEY], NULL);
        !          1955:        return(1);
        !          1956: }
1.5       kristaps 1957:
1.50    ! kristaps 1958: static void *
        !          1959: hash_halloc(size_t sz, void *arg)
        !          1960: {
1.12      schwarze 1961:
1.50    ! kristaps 1962:        return(mandoc_calloc(sz, 1));
        !          1963: }
1.12      schwarze 1964:
1.50    ! kristaps 1965: static void *
        !          1966: hash_alloc(size_t sz, void *arg)
        !          1967: {
1.5       kristaps 1968:
1.50    ! kristaps 1969:        return(mandoc_malloc(sz));
        !          1970: }
1.41      kristaps 1971:
1.50    ! kristaps 1972: static void
        !          1973: hash_free(void *p, size_t sz, void *arg)
        !          1974: {
1.4       kristaps 1975:
1.50    ! kristaps 1976:        free(p);
1.4       kristaps 1977: }
                   1978:
1.50    ! kristaps 1979: static int
        !          1980: path_reset(const char *cwd, int fd, const char *base)
1.4       kristaps 1981: {
                   1982:
1.50    ! kristaps 1983:        if (-1 == fchdir(fd)) {
        !          1984:                perror(cwd);
        !          1985:                return(0);
        !          1986:        } else if (-1 == chdir(base)) {
        !          1987:                perror(base);
        !          1988:                return(0);
1.4       kristaps 1989:        }
1.50    ! kristaps 1990:        return(1);
1.1       kristaps 1991: }

CVSweb