Annotation of src/usr.bin/mandoc/apropos_db.c, Revision 1.16
1.16 ! schwarze 1: /* $Id: apropos_db.c,v 1.15 2011/12/19 02:26:33 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 *,
114: const struct mchars *,
115: struct db_val *, 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.12 schwarze 159: btree_read(const DBT *k, const DBT *v,
160: const struct mchars *mc,
161: struct db_val *dbv, char **buf)
1.1 schwarze 162: {
1.16 ! schwarze 163: struct db_val raw_dbv;
1.1 schwarze 164:
1.12 schwarze 165: /* Are our sizes sane? */
166: if (k->size < 2 || sizeof(struct db_val) != v->size)
167: return(0);
1.8 schwarze 168:
1.12 schwarze 169: /* Is our string nil-terminated? */
170: if ('\0' != ((const char *)k->data)[(int)k->size - 1])
1.1 schwarze 171: return(0);
172:
1.12 schwarze 173: norm_string((const char *)k->data, mc, buf);
1.16 ! schwarze 174: memcpy(&raw_dbv, v->data, v->size);
! 175: dbv->rec = betoh32(raw_dbv.rec);
! 176: dbv->mask = betoh64(raw_dbv.mask);
1.1 schwarze 177: return(1);
178: }
179:
180: /*
181: * Take a Unicode codepoint and produce its UTF-8 encoding.
182: * This isn't the best way to do this, but it works.
1.8 schwarze 183: * The magic numbers are from the UTF-8 packaging.
1.1 schwarze 184: * They're not as scary as they seem: read the UTF-8 spec for details.
185: */
186: static size_t
187: norm_utf8(unsigned int cp, char out[7])
188: {
1.15 schwarze 189: int rc;
1.1 schwarze 190:
191: rc = 0;
192:
193: if (cp <= 0x0000007F) {
194: rc = 1;
195: out[0] = (char)cp;
196: } else if (cp <= 0x000007FF) {
197: rc = 2;
198: out[0] = (cp >> 6 & 31) | 192;
199: out[1] = (cp & 63) | 128;
200: } else if (cp <= 0x0000FFFF) {
201: rc = 3;
202: out[0] = (cp >> 12 & 15) | 224;
203: out[1] = (cp >> 6 & 63) | 128;
204: out[2] = (cp & 63) | 128;
205: } else if (cp <= 0x001FFFFF) {
206: rc = 4;
207: out[0] = (cp >> 18 & 7) | 240;
208: out[1] = (cp >> 12 & 63) | 128;
209: out[2] = (cp >> 6 & 63) | 128;
210: out[3] = (cp & 63) | 128;
211: } else if (cp <= 0x03FFFFFF) {
212: rc = 5;
213: out[0] = (cp >> 24 & 3) | 248;
214: out[1] = (cp >> 18 & 63) | 128;
215: out[2] = (cp >> 12 & 63) | 128;
216: out[3] = (cp >> 6 & 63) | 128;
217: out[4] = (cp & 63) | 128;
218: } else if (cp <= 0x7FFFFFFF) {
219: rc = 6;
220: out[0] = (cp >> 30 & 1) | 252;
221: out[1] = (cp >> 24 & 63) | 128;
222: out[2] = (cp >> 18 & 63) | 128;
223: out[3] = (cp >> 12 & 63) | 128;
224: out[4] = (cp >> 6 & 63) | 128;
225: out[5] = (cp & 63) | 128;
226: } else
227: return(0);
228:
229: out[rc] = '\0';
1.15 schwarze 230: return((size_t)rc);
1.1 schwarze 231: }
232:
233: /*
234: * Normalise strings from the index and database.
235: * These strings are escaped as defined by mandoc_char(7) along with
236: * other goop in mandoc.h (e.g., soft hyphens).
237: * This function normalises these into a nice UTF-8 string.
238: * Returns 0 if the database is fucked.
239: */
240: static void
241: norm_string(const char *val, const struct mchars *mc, char **buf)
242: {
243: size_t sz, bsz;
244: char utfbuf[7];
245: const char *seq, *cpp;
246: int len, u, pos;
247: enum mandoc_esc esc;
1.8 schwarze 248: static const char res[] = { '\\', '\t',
1.1 schwarze 249: ASCII_NBRSP, ASCII_HYPH, '\0' };
250:
251: /* Pre-allocate by the length of the input */
252:
253: bsz = strlen(val) + 1;
254: *buf = mandoc_realloc(*buf, bsz);
255: pos = 0;
256:
257: while ('\0' != *val) {
258: /*
259: * Halt on the first escape sequence.
260: * This also halts on the end of string, in which case
261: * we just copy, fallthrough, and exit the loop.
262: */
263: if ((sz = strcspn(val, res)) > 0) {
264: memcpy(&(*buf)[pos], val, sz);
265: pos += (int)sz;
266: val += (int)sz;
267: }
268:
269: if (ASCII_HYPH == *val) {
270: (*buf)[pos++] = '-';
271: val++;
272: continue;
273: } else if ('\t' == *val || ASCII_NBRSP == *val) {
274: (*buf)[pos++] = ' ';
275: val++;
276: continue;
277: } else if ('\\' != *val)
278: break;
279:
280: /* Read past the slash. */
281:
282: val++;
283: u = 0;
284:
285: /*
286: * Parse the escape sequence and see if it's a
287: * predefined character or special character.
288: */
289:
290: esc = mandoc_escape(&val, &seq, &len);
291: if (ESCAPE_ERROR == esc)
292: break;
293:
1.8 schwarze 294: /*
1.1 schwarze 295: * XXX - this just does UTF-8, but we need to know
296: * beforehand whether we should do text substitution.
297: */
298:
299: switch (esc) {
300: case (ESCAPE_SPECIAL):
301: if (0 != (u = mchars_spec2cp(mc, seq, len)))
302: break;
303: /* FALLTHROUGH */
304: default:
305: continue;
306: }
307:
308: /*
309: * If we have a Unicode codepoint, try to convert that
310: * to a UTF-8 byte string.
311: */
312:
313: cpp = utfbuf;
314: if (0 == (sz = norm_utf8(u, utfbuf)))
315: continue;
316:
317: /* Copy the rendered glyph into the stream. */
318:
319: sz = strlen(cpp);
320: bsz += sz;
321:
322: *buf = mandoc_realloc(*buf, bsz);
323:
324: memcpy(&(*buf)[pos], cpp, sz);
325: pos += (int)sz;
326: }
327:
328: (*buf)[pos] = '\0';
329: }
330:
331: /*
332: * Open the filename-index mandoc-db database.
333: * Returns NULL if opening failed.
334: */
335: static DB *
336: index_open(void)
337: {
338: DB *db;
339:
1.2 schwarze 340: db = dbopen(MANDOC_IDX, O_RDONLY, 0, DB_RECNO, NULL);
1.1 schwarze 341: if (NULL != db)
342: return(db);
343:
344: return(NULL);
345: }
346:
347: /*
348: * Safely unpack from an index file record into the structure.
349: * Returns 1 if an entry was unpacked, 0 if the database is insane.
350: */
351: static int
1.8 schwarze 352: index_read(const DBT *key, const DBT *val, int index,
1.1 schwarze 353: const struct mchars *mc, struct rec *rec)
354: {
355: size_t left;
356: char *np, *cp;
1.15 schwarze 357: char type;
1.1 schwarze 358:
359: #define INDEX_BREAD(_dst) \
360: do { \
361: if (NULL == (np = memchr(cp, '\0', left))) \
362: return(0); \
363: norm_string(cp, mc, &(_dst)); \
364: left -= (np - cp) + 1; \
365: cp = np + 1; \
366: } while (/* CONSTCOND */ 0)
367:
1.15 schwarze 368: if (0 == (left = val->size))
369: return(0);
1.1 schwarze 370:
1.15 schwarze 371: cp = val->data;
1.16 ! schwarze 372: assert(sizeof(recno_t) == key->size);
! 373: memcpy(&rec->res.rec, key->data, key->size);
1.8 schwarze 374: rec->res.volume = index;
1.1 schwarze 375:
1.15 schwarze 376: if ('d' == (type = *cp++))
377: rec->res.type = RESTYPE_MDOC;
378: else if ('a' == type)
379: rec->res.type = RESTYPE_MAN;
380: else if ('c' == type)
381: rec->res.type = RESTYPE_CAT;
382: else
383: return(0);
384:
385: left--;
1.7 schwarze 386: INDEX_BREAD(rec->res.file);
387: INDEX_BREAD(rec->res.cat);
388: INDEX_BREAD(rec->res.title);
389: INDEX_BREAD(rec->res.arch);
390: INDEX_BREAD(rec->res.desc);
1.1 schwarze 391: return(1);
392: }
393:
394: /*
1.8 schwarze 395: * Search mandocdb databases in paths for expression "expr".
1.1 schwarze 396: * Filter out by "opts".
397: * Call "res" with the results, which may be zero.
1.7 schwarze 398: * Return 0 if there was a database error, else return 1.
1.1 schwarze 399: */
1.7 schwarze 400: int
1.8 schwarze 401: apropos_search(int pathsz, char **paths, const struct opts *opts,
402: const struct expr *expr, size_t terms, void *arg,
1.7 schwarze 403: void (*res)(struct res *, size_t, void *))
1.1 schwarze 404: {
1.5 schwarze 405: struct rectree tree;
406: struct mchars *mc;
1.7 schwarze 407: struct res *ress;
408: int i, mlen, rc;
1.5 schwarze 409:
410: memset(&tree, 0, sizeof(struct rectree));
411:
1.8 schwarze 412: rc = 0;
1.5 schwarze 413: mc = mchars_alloc();
414:
1.8 schwarze 415: /*
416: * Main loop. Change into the directory containing manpage
417: * databases. Run our expession over each database in the set.
418: */
419:
420: for (i = 0; i < pathsz; i++) {
421: if (chdir(paths[i]))
1.5 schwarze 422: continue;
1.8 schwarze 423: if ( ! single_search(&tree, opts, expr, terms, mc, i))
424: goto out;
1.5 schwarze 425: }
426:
427: /*
1.8 schwarze 428: * Count matching files, transfer to a "clean" array, then feed
429: * them to the output handler.
1.5 schwarze 430: */
431:
432: for (mlen = i = 0; i < tree.len; i++)
1.7 schwarze 433: if (tree.node[i].matched)
1.5 schwarze 434: mlen++;
1.8 schwarze 435:
1.7 schwarze 436: ress = mandoc_malloc(mlen * sizeof(struct res));
1.8 schwarze 437:
1.5 schwarze 438: for (mlen = i = 0; i < tree.len; i++)
1.7 schwarze 439: if (tree.node[i].matched)
1.8 schwarze 440: memcpy(&ress[mlen++], &tree.node[i].res,
1.7 schwarze 441: sizeof(struct res));
1.8 schwarze 442:
1.7 schwarze 443: (*res)(ress, mlen, arg);
444: free(ress);
1.5 schwarze 445:
1.8 schwarze 446: rc = 1;
447: out:
1.5 schwarze 448: for (i = 0; i < tree.len; i++)
449: recfree(&tree.node[i]);
450:
1.8 schwarze 451: free(tree.node);
452: mchars_free(mc);
1.7 schwarze 453: return(rc);
1.5 schwarze 454: }
455:
1.7 schwarze 456: static int
1.5 schwarze 457: single_search(struct rectree *tree, const struct opts *opts,
458: const struct expr *expr, size_t terms,
1.8 schwarze 459: struct mchars *mc, int vol)
1.5 schwarze 460: {
1.8 schwarze 461: int root, leaf, ch;
1.1 schwarze 462: DBT key, val;
463: DB *btree, *idx;
464: char *buf;
1.7 schwarze 465: struct rec *rs;
466: struct rec r;
1.12 schwarze 467: struct db_val vb;
1.1 schwarze 468:
469: root = -1;
470: leaf = -1;
471: btree = NULL;
472: idx = NULL;
473: buf = NULL;
1.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.12 schwarze 487: if ( ! btree_read(&key, &val, mc, &vb, &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.12 schwarze 494: if ( ! exprmark(expr, buf, vb.mask, NULL))
1.1 schwarze 495: continue;
496:
497: /*
498: * O(log n) scan for prior records. Since a record
499: * number is unbounded, this has decent performance over
500: * a complex hash function.
501: */
502:
503: for (leaf = root; leaf >= 0; )
1.12 schwarze 504: if (vb.rec > rs[leaf].res.rec &&
1.7 schwarze 505: rs[leaf].rhs >= 0)
506: leaf = rs[leaf].rhs;
1.12 schwarze 507: else if (vb.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.12 schwarze 519: if (leaf >= 0 && rs[leaf].res.rec == vb.rec) {
1.7 schwarze 520: if (0 == rs[leaf].matched)
1.12 schwarze 521: exprexec(expr, buf, vb.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.12 schwarze 531: key.data = &vb.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.12 schwarze 558: exprexec(expr, buf, vb.mask, &rs[tree->len]);
1.1 schwarze 559:
560: /* Append to our tree. */
561:
562: if (leaf >= 0) {
1.12 schwarze 563: if (vb.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: }