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