]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/mdocml/mansearch.c
Update mandoc to cvs snaphot from 20150302
[FreeBSD/FreeBSD.git] / contrib / mdocml / mansearch.c
1 /*      $Id: mansearch.c,v 1.54 2015/02/27 16:02:10 schwarze Exp $ */
2 /*
3  * Copyright (c) 2012 Kristaps Dzonsons <kristaps@bsd.lv>
4  * Copyright (c) 2013, 2014, 2015 Ingo Schwarze <schwarze@openbsd.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 #include "config.h"
19
20 #include <sys/mman.h>
21 #include <sys/types.h>
22
23 #include <assert.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <getopt.h>
27 #include <glob.h>
28 #include <limits.h>
29 #include <regex.h>
30 #include <stdio.h>
31 #include <stdint.h>
32 #include <stddef.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36
37 #if HAVE_OHASH
38 #include <ohash.h>
39 #else
40 #include "compat_ohash.h"
41 #endif
42 #include <sqlite3.h>
43 #ifndef SQLITE_DETERMINISTIC
44 #define SQLITE_DETERMINISTIC 0
45 #endif
46
47 #include "mandoc.h"
48 #include "mandoc_aux.h"
49 #include "manpath.h"
50 #include "mansearch.h"
51
52 extern int mansearch_keymax;
53 extern const char *const mansearch_keynames[];
54
55 #define SQL_BIND_TEXT(_db, _s, _i, _v) \
56         do { if (SQLITE_OK != sqlite3_bind_text \
57                 ((_s), (_i)++, (_v), -1, SQLITE_STATIC)) \
58                 fprintf(stderr, "%s\n", sqlite3_errmsg((_db))); \
59         } while (0)
60 #define SQL_BIND_INT64(_db, _s, _i, _v) \
61         do { if (SQLITE_OK != sqlite3_bind_int64 \
62                 ((_s), (_i)++, (_v))) \
63                 fprintf(stderr, "%s\n", sqlite3_errmsg((_db))); \
64         } while (0)
65 #define SQL_BIND_BLOB(_db, _s, _i, _v) \
66         do { if (SQLITE_OK != sqlite3_bind_blob \
67                 ((_s), (_i)++, (&_v), sizeof(_v), SQLITE_STATIC)) \
68                 fprintf(stderr, "%s\n", sqlite3_errmsg((_db))); \
69         } while (0)
70
71 struct  expr {
72         regex_t          regexp;  /* compiled regexp, if applicable */
73         const char      *substr;  /* to search for, if applicable */
74         struct expr     *next;    /* next in sequence */
75         uint64_t         bits;    /* type-mask */
76         int              equal;   /* equality, not subsring match */
77         int              open;    /* opening parentheses before */
78         int              and;     /* logical AND before */
79         int              close;   /* closing parentheses after */
80 };
81
82 struct  match {
83         uint64_t         pageid; /* identifier in database */
84         uint64_t         bits; /* name type mask */
85         char            *desc; /* manual page description */
86         int              form; /* bit field: formatted, zipped? */
87 };
88
89 static  void             buildnames(const struct mansearch *,
90                                 struct manpage *, sqlite3 *,
91                                 sqlite3_stmt *, uint64_t,
92                                 const char *, int form);
93 static  char            *buildoutput(sqlite3 *, sqlite3_stmt *,
94                                  uint64_t, uint64_t);
95 static  void            *hash_alloc(size_t, void *);
96 static  void             hash_free(void *, void *);
97 static  void            *hash_calloc(size_t, size_t, void *);
98 static  struct expr     *exprcomp(const struct mansearch *,
99                                 int, char *[]);
100 static  void             exprfree(struct expr *);
101 static  struct expr     *exprterm(const struct mansearch *, char *, int);
102 static  int              manpage_compare(const void *, const void *);
103 static  void             sql_append(char **sql, size_t *sz,
104                                 const char *newstr, int count);
105 static  void             sql_match(sqlite3_context *context,
106                                 int argc, sqlite3_value **argv);
107 static  void             sql_regexp(sqlite3_context *context,
108                                 int argc, sqlite3_value **argv);
109 static  char            *sql_statement(const struct expr *);
110
111
112 int
113 mansearch_setup(int start)
114 {
115         static void     *pagecache;
116         int              c;
117
118 #define PC_PAGESIZE     1280
119 #define PC_NUMPAGES     256
120
121         if (start) {
122                 if (NULL != pagecache) {
123                         fprintf(stderr, "pagecache already enabled\n");
124                         return((int)MANDOCLEVEL_BADARG);
125                 }
126
127                 pagecache = mmap(NULL, PC_PAGESIZE * PC_NUMPAGES,
128                     PROT_READ | PROT_WRITE,
129                     MAP_SHARED | MAP_ANON, -1, 0);
130
131                 if (MAP_FAILED == pagecache) {
132                         perror("mmap");
133                         pagecache = NULL;
134                         return((int)MANDOCLEVEL_SYSERR);
135                 }
136
137                 c = sqlite3_config(SQLITE_CONFIG_PAGECACHE,
138                     pagecache, PC_PAGESIZE, PC_NUMPAGES);
139
140                 if (SQLITE_OK == c)
141                         return((int)MANDOCLEVEL_OK);
142
143                 fprintf(stderr, "pagecache: %s\n", sqlite3_errstr(c));
144
145         } else if (NULL == pagecache) {
146                 fprintf(stderr, "pagecache missing\n");
147                 return((int)MANDOCLEVEL_BADARG);
148         }
149
150         if (-1 == munmap(pagecache, PC_PAGESIZE * PC_NUMPAGES)) {
151                 perror("munmap");
152                 pagecache = NULL;
153                 return((int)MANDOCLEVEL_SYSERR);
154         }
155
156         pagecache = NULL;
157         return((int)MANDOCLEVEL_OK);
158 }
159
160 int
161 mansearch(const struct mansearch *search,
162                 const struct manpaths *paths,
163                 int argc, char *argv[],
164                 struct manpage **res, size_t *sz)
165 {
166         int              fd, rc, c, indexbit;
167         int64_t          pageid;
168         uint64_t         outbit, iterbit;
169         char             buf[PATH_MAX];
170         char            *sql;
171         struct manpage  *mpage;
172         struct expr     *e, *ep;
173         sqlite3         *db;
174         sqlite3_stmt    *s, *s2;
175         struct match    *mp;
176         struct ohash_info info;
177         struct ohash     htab;
178         unsigned int     idx;
179         size_t           i, j, cur, maxres;
180
181         info.calloc = hash_calloc;
182         info.alloc = hash_alloc;
183         info.free = hash_free;
184         info.key_offset = offsetof(struct match, pageid);
185
186         *sz = cur = maxres = 0;
187         sql = NULL;
188         *res = NULL;
189         fd = -1;
190         e = NULL;
191         rc = 0;
192
193         if (0 == argc)
194                 goto out;
195         if (NULL == (e = exprcomp(search, argc, argv)))
196                 goto out;
197
198         outbit = 0;
199         if (NULL != search->outkey) {
200                 for (indexbit = 0, iterbit = 1;
201                      indexbit < mansearch_keymax;
202                      indexbit++, iterbit <<= 1) {
203                         if (0 == strcasecmp(search->outkey,
204                             mansearch_keynames[indexbit])) {
205                                 outbit = iterbit;
206                                 break;
207                         }
208                 }
209         }
210
211         /*
212          * Save a descriptor to the current working directory.
213          * Since pathnames in the "paths" variable might be relative,
214          * and we'll be chdir()ing into them, we need to keep a handle
215          * on our current directory from which to start the chdir().
216          */
217
218         if (NULL == getcwd(buf, PATH_MAX)) {
219                 perror("getcwd");
220                 goto out;
221         } else if (-1 == (fd = open(buf, O_RDONLY, 0))) {
222                 perror(buf);
223                 goto out;
224         }
225
226         sql = sql_statement(e);
227
228         /*
229          * Loop over the directories (containing databases) for us to
230          * search.
231          * Don't let missing/bad databases/directories phase us.
232          * In each, try to open the resident database and, if it opens,
233          * scan it for our match expression.
234          */
235
236         for (i = 0; i < paths->sz; i++) {
237                 if (-1 == fchdir(fd)) {
238                         perror(buf);
239                         free(*res);
240                         break;
241                 } else if (-1 == chdir(paths->paths[i])) {
242                         perror(paths->paths[i]);
243                         continue;
244                 }
245
246                 c = sqlite3_open_v2(MANDOC_DB, &db,
247                     SQLITE_OPEN_READONLY, NULL);
248
249                 if (SQLITE_OK != c) {
250                         fprintf(stderr, "%s/%s: %s\n",
251                             paths->paths[i], MANDOC_DB, strerror(errno));
252                         sqlite3_close(db);
253                         continue;
254                 }
255
256                 /*
257                  * Define the SQL functions for substring
258                  * and regular expression matching.
259                  */
260
261                 c = sqlite3_create_function(db, "match", 2,
262                     SQLITE_UTF8 | SQLITE_DETERMINISTIC,
263                     NULL, sql_match, NULL, NULL);
264                 assert(SQLITE_OK == c);
265                 c = sqlite3_create_function(db, "regexp", 2,
266                     SQLITE_UTF8 | SQLITE_DETERMINISTIC,
267                     NULL, sql_regexp, NULL, NULL);
268                 assert(SQLITE_OK == c);
269
270                 j = 1;
271                 c = sqlite3_prepare_v2(db, sql, -1, &s, NULL);
272                 if (SQLITE_OK != c)
273                         fprintf(stderr, "%s\n", sqlite3_errmsg(db));
274
275                 for (ep = e; NULL != ep; ep = ep->next) {
276                         if (NULL == ep->substr) {
277                                 SQL_BIND_BLOB(db, s, j, ep->regexp);
278                         } else
279                                 SQL_BIND_TEXT(db, s, j, ep->substr);
280                         if (0 == ((TYPE_Nd | TYPE_Nm) & ep->bits))
281                                 SQL_BIND_INT64(db, s, j, ep->bits);
282                 }
283
284                 memset(&htab, 0, sizeof(struct ohash));
285                 ohash_init(&htab, 4, &info);
286
287                 /*
288                  * Hash each entry on its [unique] document identifier.
289                  * This is a uint64_t.
290                  * Instead of using a hash function, simply convert the
291                  * uint64_t to a uint32_t, the hash value's type.
292                  * This gives good performance and preserves the
293                  * distribution of buckets in the table.
294                  */
295                 while (SQLITE_ROW == (c = sqlite3_step(s))) {
296                         pageid = sqlite3_column_int64(s, 2);
297                         idx = ohash_lookup_memory(&htab,
298                             (char *)&pageid, sizeof(uint64_t),
299                             (uint32_t)pageid);
300
301                         if (NULL != ohash_find(&htab, idx))
302                                 continue;
303
304                         mp = mandoc_calloc(1, sizeof(struct match));
305                         mp->pageid = pageid;
306                         mp->form = sqlite3_column_int(s, 1);
307                         mp->bits = sqlite3_column_int64(s, 3);
308                         if (TYPE_Nd == outbit)
309                                 mp->desc = mandoc_strdup((const char *)
310                                     sqlite3_column_text(s, 0));
311                         ohash_insert(&htab, idx, mp);
312                 }
313
314                 if (SQLITE_DONE != c)
315                         fprintf(stderr, "%s\n", sqlite3_errmsg(db));
316
317                 sqlite3_finalize(s);
318
319                 c = sqlite3_prepare_v2(db,
320                     "SELECT sec, arch, name, pageid FROM mlinks "
321                     "WHERE pageid=? ORDER BY sec, arch, name",
322                     -1, &s, NULL);
323                 if (SQLITE_OK != c)
324                         fprintf(stderr, "%s\n", sqlite3_errmsg(db));
325
326                 c = sqlite3_prepare_v2(db,
327                     "SELECT bits, key, pageid FROM keys "
328                     "WHERE pageid=? AND bits & ?",
329                     -1, &s2, NULL);
330                 if (SQLITE_OK != c)
331                         fprintf(stderr, "%s\n", sqlite3_errmsg(db));
332
333                 for (mp = ohash_first(&htab, &idx);
334                                 NULL != mp;
335                                 mp = ohash_next(&htab, &idx)) {
336                         if (cur + 1 > maxres) {
337                                 maxres += 1024;
338                                 *res = mandoc_reallocarray(*res,
339                                     maxres, sizeof(struct manpage));
340                         }
341                         mpage = *res + cur;
342                         mpage->ipath = i;
343                         mpage->bits = mp->bits;
344                         mpage->sec = 10;
345                         mpage->form = mp->form;
346                         buildnames(search, mpage, db, s, mp->pageid,
347                             paths->paths[i], mp->form);
348                         if (mpage->names != NULL) {
349                                 mpage->output = TYPE_Nd & outbit ?
350                                     mp->desc : outbit ?
351                                     buildoutput(db, s2, mp->pageid, outbit) :
352                                     NULL;
353                                 cur++;
354                         }
355                         free(mp);
356                 }
357
358                 sqlite3_finalize(s);
359                 sqlite3_finalize(s2);
360                 sqlite3_close(db);
361                 ohash_delete(&htab);
362
363                 /*
364                  * In man(1) mode, prefer matches in earlier trees
365                  * over matches in later trees.
366                  */
367
368                 if (cur && search->firstmatch)
369                         break;
370         }
371         qsort(*res, cur, sizeof(struct manpage), manpage_compare);
372         rc = 1;
373 out:
374         if (-1 != fd) {
375                 if (-1 == fchdir(fd))
376                         perror(buf);
377                 close(fd);
378         }
379         exprfree(e);
380         free(sql);
381         *sz = cur;
382         return(rc);
383 }
384
385 void
386 mansearch_free(struct manpage *res, size_t sz)
387 {
388         size_t   i;
389
390         for (i = 0; i < sz; i++) {
391                 free(res[i].file);
392                 free(res[i].names);
393                 free(res[i].output);
394         }
395         free(res);
396 }
397
398 static int
399 manpage_compare(const void *vp1, const void *vp2)
400 {
401         const struct manpage    *mp1, *mp2;
402         int                      diff;
403
404         mp1 = vp1;
405         mp2 = vp2;
406         return( (diff = mp2->bits - mp1->bits) ? diff :
407                 (diff = mp1->sec - mp2->sec) ? diff :
408                 strcasecmp(mp1->names, mp2->names));
409 }
410
411 static void
412 buildnames(const struct mansearch *search, struct manpage *mpage,
413                 sqlite3 *db, sqlite3_stmt *s,
414                 uint64_t pageid, const char *path, int form)
415 {
416         glob_t           globinfo;
417         char            *firstname, *newnames, *prevsec, *prevarch;
418         const char      *oldnames, *sep1, *name, *sec, *sep2, *arch, *fsec;
419         size_t           i;
420         int              c, globres;
421
422         mpage->file = NULL;
423         mpage->names = NULL;
424         firstname = prevsec = prevarch = NULL;
425         i = 1;
426         SQL_BIND_INT64(db, s, i, pageid);
427         while (SQLITE_ROW == (c = sqlite3_step(s))) {
428
429                 /* Decide whether we already have some names. */
430
431                 if (NULL == mpage->names) {
432                         oldnames = "";
433                         sep1 = "";
434                 } else {
435                         oldnames = mpage->names;
436                         sep1 = ", ";
437                 }
438
439                 /* Fetch the next name, rejecting sec/arch mismatches. */
440
441                 sec = (const char *)sqlite3_column_text(s, 0);
442                 if (search->sec != NULL && strcasecmp(sec, search->sec))
443                         continue;
444                 arch = (const char *)sqlite3_column_text(s, 1);
445                 if (search->arch != NULL && *arch != '\0' &&
446                     strcasecmp(arch, search->arch))
447                         continue;
448                 name = (const char *)sqlite3_column_text(s, 2);
449
450                 /* Remember the first section found. */
451
452                 if (9 < mpage->sec && '1' <= *sec && '9' >= *sec)
453                         mpage->sec = (*sec - '1') + 1;
454
455                 /* If the section changed, append the old one. */
456
457                 if (NULL != prevsec &&
458                     (strcmp(sec, prevsec) ||
459                      strcmp(arch, prevarch))) {
460                         sep2 = '\0' == *prevarch ? "" : "/";
461                         mandoc_asprintf(&newnames, "%s(%s%s%s)",
462                             oldnames, prevsec, sep2, prevarch);
463                         free(mpage->names);
464                         oldnames = mpage->names = newnames;
465                         free(prevsec);
466                         free(prevarch);
467                         prevsec = prevarch = NULL;
468                 }
469
470                 /* Save the new section, to append it later. */
471
472                 if (NULL == prevsec) {
473                         prevsec = mandoc_strdup(sec);
474                         prevarch = mandoc_strdup(arch);
475                 }
476
477                 /* Append the new name. */
478
479                 mandoc_asprintf(&newnames, "%s%s%s",
480                     oldnames, sep1, name);
481                 free(mpage->names);
482                 mpage->names = newnames;
483
484                 /* Also save the first file name encountered. */
485
486                 if (mpage->file != NULL)
487                         continue;
488
489                 if (form & FORM_SRC) {
490                         sep1 = "man";
491                         fsec = sec;
492                 } else {
493                         sep1 = "cat";
494                         fsec = "0";
495                 }
496                 sep2 = *arch == '\0' ? "" : "/";
497                 mandoc_asprintf(&mpage->file, "%s/%s%s%s%s/%s.%s",
498                     path, sep1, sec, sep2, arch, name, fsec);
499                 if (access(mpage->file, R_OK) != -1)
500                         continue;
501
502                 /* Handle unusual file name extensions. */
503
504                 if (firstname == NULL)
505                         firstname = mpage->file;
506                 else
507                         free(mpage->file);
508                 mandoc_asprintf(&mpage->file, "%s/%s%s%s%s/%s.*",
509                     path, sep1, sec, sep2, arch, name);
510                 globres = glob(mpage->file, 0, NULL, &globinfo);
511                 free(mpage->file);
512                 mpage->file = globres ? NULL :
513                     mandoc_strdup(*globinfo.gl_pathv);
514                 globfree(&globinfo);
515         }
516         if (c != SQLITE_DONE)
517                 fprintf(stderr, "%s\n", sqlite3_errmsg(db));
518         sqlite3_reset(s);
519
520         /* If none of the files is usable, use the first name. */
521
522         if (mpage->file == NULL)
523                 mpage->file = firstname;
524         else if (mpage->file != firstname)
525                 free(firstname);
526
527         /* Append one final section to the names. */
528
529         if (prevsec != NULL) {
530                 sep2 = *prevarch == '\0' ? "" : "/";
531                 mandoc_asprintf(&newnames, "%s(%s%s%s)",
532                     mpage->names, prevsec, sep2, prevarch);
533                 free(mpage->names);
534                 mpage->names = newnames;
535                 free(prevsec);
536                 free(prevarch);
537         }
538 }
539
540 static char *
541 buildoutput(sqlite3 *db, sqlite3_stmt *s, uint64_t pageid, uint64_t outbit)
542 {
543         char            *output, *newoutput;
544         const char      *oldoutput, *sep1, *data;
545         size_t           i;
546         int              c;
547
548         output = NULL;
549         i = 1;
550         SQL_BIND_INT64(db, s, i, pageid);
551         SQL_BIND_INT64(db, s, i, outbit);
552         while (SQLITE_ROW == (c = sqlite3_step(s))) {
553                 if (NULL == output) {
554                         oldoutput = "";
555                         sep1 = "";
556                 } else {
557                         oldoutput = output;
558                         sep1 = " # ";
559                 }
560                 data = (const char *)sqlite3_column_text(s, 1);
561                 mandoc_asprintf(&newoutput, "%s%s%s",
562                     oldoutput, sep1, data);
563                 free(output);
564                 output = newoutput;
565         }
566         if (SQLITE_DONE != c)
567                 fprintf(stderr, "%s\n", sqlite3_errmsg(db));
568         sqlite3_reset(s);
569         return(output);
570 }
571
572 /*
573  * Implement substring match as an application-defined SQL function.
574  * Using the SQL LIKE or GLOB operators instead would be a bad idea
575  * because that would require escaping metacharacters in the string
576  * being searched for.
577  */
578 static void
579 sql_match(sqlite3_context *context, int argc, sqlite3_value **argv)
580 {
581
582         assert(2 == argc);
583         sqlite3_result_int(context, NULL != strcasestr(
584             (const char *)sqlite3_value_text(argv[1]),
585             (const char *)sqlite3_value_text(argv[0])));
586 }
587
588 /*
589  * Implement regular expression match
590  * as an application-defined SQL function.
591  */
592 static void
593 sql_regexp(sqlite3_context *context, int argc, sqlite3_value **argv)
594 {
595
596         assert(2 == argc);
597         sqlite3_result_int(context, !regexec(
598             (regex_t *)sqlite3_value_blob(argv[0]),
599             (const char *)sqlite3_value_text(argv[1]),
600             0, NULL, 0));
601 }
602
603 static void
604 sql_append(char **sql, size_t *sz, const char *newstr, int count)
605 {
606         size_t           newsz;
607
608         newsz = 1 < count ? (size_t)count : strlen(newstr);
609         *sql = mandoc_realloc(*sql, *sz + newsz + 1);
610         if (1 < count)
611                 memset(*sql + *sz, *newstr, (size_t)count);
612         else
613                 memcpy(*sql + *sz, newstr, newsz);
614         *sz += newsz;
615         (*sql)[*sz] = '\0';
616 }
617
618 /*
619  * Prepare the search SQL statement.
620  */
621 static char *
622 sql_statement(const struct expr *e)
623 {
624         char            *sql;
625         size_t           sz;
626         int              needop;
627
628         sql = mandoc_strdup(e->equal ?
629             "SELECT desc, form, pageid, bits "
630                 "FROM mpages NATURAL JOIN names WHERE " :
631             "SELECT desc, form, pageid, 0 FROM mpages WHERE ");
632         sz = strlen(sql);
633
634         for (needop = 0; NULL != e; e = e->next) {
635                 if (e->and)
636                         sql_append(&sql, &sz, " AND ", 1);
637                 else if (needop)
638                         sql_append(&sql, &sz, " OR ", 1);
639                 if (e->open)
640                         sql_append(&sql, &sz, "(", e->open);
641                 sql_append(&sql, &sz,
642                     TYPE_Nd & e->bits
643                     ? (NULL == e->substr
644                         ? "desc REGEXP ?"
645                         : "desc MATCH ?")
646                     : TYPE_Nm == e->bits
647                     ? (NULL == e->substr
648                         ? "pageid IN (SELECT pageid FROM names "
649                           "WHERE name REGEXP ?)"
650                         : e->equal
651                         ? "name = ? "
652                         : "pageid IN (SELECT pageid FROM names "
653                           "WHERE name MATCH ?)")
654                     : (NULL == e->substr
655                         ? "pageid IN (SELECT pageid FROM keys "
656                           "WHERE key REGEXP ? AND bits & ?)"
657                         : "pageid IN (SELECT pageid FROM keys "
658                           "WHERE key MATCH ? AND bits & ?)"), 1);
659                 if (e->close)
660                         sql_append(&sql, &sz, ")", e->close);
661                 needop = 1;
662         }
663
664         return(sql);
665 }
666
667 /*
668  * Compile a set of string tokens into an expression.
669  * Tokens in "argv" are assumed to be individual expression atoms (e.g.,
670  * "(", "foo=bar", etc.).
671  */
672 static struct expr *
673 exprcomp(const struct mansearch *search, int argc, char *argv[])
674 {
675         uint64_t         mask;
676         int              i, toopen, logic, igncase, toclose;
677         struct expr     *first, *prev, *cur, *next;
678
679         first = cur = NULL;
680         logic = igncase = toopen = toclose = 0;
681
682         for (i = 0; i < argc; i++) {
683                 if (0 == strcmp("(", argv[i])) {
684                         if (igncase)
685                                 goto fail;
686                         toopen++;
687                         toclose++;
688                         continue;
689                 } else if (0 == strcmp(")", argv[i])) {
690                         if (toopen || logic || igncase || NULL == cur)
691                                 goto fail;
692                         cur->close++;
693                         if (0 > --toclose)
694                                 goto fail;
695                         continue;
696                 } else if (0 == strcmp("-a", argv[i])) {
697                         if (toopen || logic || igncase || NULL == cur)
698                                 goto fail;
699                         logic = 1;
700                         continue;
701                 } else if (0 == strcmp("-o", argv[i])) {
702                         if (toopen || logic || igncase || NULL == cur)
703                                 goto fail;
704                         logic = 2;
705                         continue;
706                 } else if (0 == strcmp("-i", argv[i])) {
707                         if (igncase)
708                                 goto fail;
709                         igncase = 1;
710                         continue;
711                 }
712                 next = exprterm(search, argv[i], !igncase);
713                 if (NULL == next)
714                         goto fail;
715                 if (NULL == first)
716                         first = next;
717                 else
718                         cur->next = next;
719                 prev = cur = next;
720
721                 /*
722                  * Searching for descriptions must be split out
723                  * because they are stored in the mpages table,
724                  * not in the keys table.
725                  */
726
727                 for (mask = TYPE_Nm; mask <= TYPE_Nd; mask <<= 1) {
728                         if (mask & cur->bits && ~mask & cur->bits) {
729                                 next = mandoc_calloc(1,
730                                     sizeof(struct expr));
731                                 memcpy(next, cur, sizeof(struct expr));
732                                 prev->open = 1;
733                                 cur->bits = mask;
734                                 cur->next = next;
735                                 cur = next;
736                                 cur->bits &= ~mask;
737                         }
738                 }
739                 prev->and = (1 == logic);
740                 prev->open += toopen;
741                 if (cur != prev)
742                         cur->close = 1;
743
744                 toopen = logic = igncase = 0;
745         }
746         if ( ! (toopen || logic || igncase || toclose))
747                 return(first);
748
749 fail:
750         if (NULL != first)
751                 exprfree(first);
752         return(NULL);
753 }
754
755 static struct expr *
756 exprterm(const struct mansearch *search, char *buf, int cs)
757 {
758         char             errbuf[BUFSIZ];
759         struct expr     *e;
760         char            *key, *val;
761         uint64_t         iterbit;
762         int              i, irc;
763
764         if ('\0' == *buf)
765                 return(NULL);
766
767         e = mandoc_calloc(1, sizeof(struct expr));
768
769         if (search->argmode == ARG_NAME) {
770                 e->bits = TYPE_Nm;
771                 e->substr = buf;
772                 e->equal = 1;
773                 return(e);
774         }
775
776         /*
777          * Separate macro keys from search string.
778          * If needed, request regular expression handling
779          * by setting e->substr to NULL.
780          */
781
782         if (search->argmode == ARG_WORD) {
783                 e->bits = TYPE_Nm;
784                 e->substr = NULL;
785                 mandoc_asprintf(&val, "[[:<:]]%s[[:>:]]", buf);
786                 cs = 0;
787         } else if ((val = strpbrk(buf, "=~")) == NULL) {
788                 e->bits = TYPE_Nm | TYPE_Nd;
789                 e->substr = buf;
790         } else {
791                 if (val == buf)
792                         e->bits = TYPE_Nm | TYPE_Nd;
793                 if ('=' == *val)
794                         e->substr = val + 1;
795                 *val++ = '\0';
796                 if (NULL != strstr(buf, "arch"))
797                         cs = 0;
798         }
799
800         /* Compile regular expressions. */
801
802         if (NULL == e->substr) {
803                 irc = regcomp(&e->regexp, val,
804                     REG_EXTENDED | REG_NOSUB | (cs ? 0 : REG_ICASE));
805                 if (search->argmode == ARG_WORD)
806                         free(val);
807                 if (irc) {
808                         regerror(irc, &e->regexp, errbuf, sizeof(errbuf));
809                         fprintf(stderr, "regcomp: %s\n", errbuf);
810                         free(e);
811                         return(NULL);
812                 }
813         }
814
815         if (e->bits)
816                 return(e);
817
818         /*
819          * Parse out all possible fields.
820          * If the field doesn't resolve, bail.
821          */
822
823         while (NULL != (key = strsep(&buf, ","))) {
824                 if ('\0' == *key)
825                         continue;
826                 for (i = 0, iterbit = 1;
827                      i < mansearch_keymax;
828                      i++, iterbit <<= 1) {
829                         if (0 == strcasecmp(key,
830                             mansearch_keynames[i])) {
831                                 e->bits |= iterbit;
832                                 break;
833                         }
834                 }
835                 if (i == mansearch_keymax) {
836                         if (strcasecmp(key, "any")) {
837                                 free(e);
838                                 return(NULL);
839                         }
840                         e->bits |= ~0ULL;
841                 }
842         }
843
844         return(e);
845 }
846
847 static void
848 exprfree(struct expr *p)
849 {
850         struct expr     *pp;
851
852         while (NULL != p) {
853                 pp = p->next;
854                 free(p);
855                 p = pp;
856         }
857 }
858
859 static void *
860 hash_calloc(size_t nmemb, size_t sz, void *arg)
861 {
862
863         return(mandoc_calloc(nmemb, sz));
864 }
865
866 static void *
867 hash_alloc(size_t sz, void *arg)
868 {
869
870         return(mandoc_malloc(sz));
871 }
872
873 static void
874 hash_free(void *p, void *arg)
875 {
876
877         free(p);
878 }