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