Annotation of src/usr.bin/mandoc/apropos_db.c, Revision 1.15
1.15 ! schwarze 1: /* $Id: apropos_db.c,v 1.14 2011/12/10 22:18:20 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.12 schwarze 163: const struct db_val *vp;
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: vp = v->data;
174: norm_string((const char *)k->data, mc, buf);
175: dbv->rec = betoh32(vp->rec);
176: dbv->mask = betoh64(vp->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.7 schwarze 372: rec->res.rec = *(recno_t *)key->data;
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.12 schwarze 466: struct db_val vb;
1.1 schwarze 467:
468: root = -1;
469: leaf = -1;
470: btree = NULL;
471: idx = NULL;
472: buf = NULL;
1.7 schwarze 473: rs = tree->node;
1.1 schwarze 474:
1.7 schwarze 475: memset(&r, 0, sizeof(struct rec));
1.1 schwarze 476:
1.8 schwarze 477: if (NULL == (btree = btree_open()))
478: return(1);
479:
480: if (NULL == (idx = index_open())) {
481: (*btree->close)(btree);
482: return(1);
483: }
1.1 schwarze 484:
1.8 schwarze 485: while (0 == (ch = (*btree->seq)(btree, &key, &val, R_NEXT))) {
1.12 schwarze 486: if ( ! btree_read(&key, &val, mc, &vb, &buf))
1.8 schwarze 487: break;
488:
1.4 schwarze 489: /*
490: * See if this keyword record matches any of the
491: * expressions we have stored.
492: */
1.12 schwarze 493: if ( ! exprmark(expr, buf, vb.mask, NULL))
1.1 schwarze 494: continue;
495:
496: /*
497: * O(log n) scan for prior records. Since a record
498: * number is unbounded, this has decent performance over
499: * a complex hash function.
500: */
501:
502: for (leaf = root; leaf >= 0; )
1.12 schwarze 503: if (vb.rec > rs[leaf].res.rec &&
1.7 schwarze 504: rs[leaf].rhs >= 0)
505: leaf = rs[leaf].rhs;
1.12 schwarze 506: else if (vb.rec < rs[leaf].res.rec &&
1.7 schwarze 507: rs[leaf].lhs >= 0)
508: leaf = rs[leaf].lhs;
1.8 schwarze 509: else
1.1 schwarze 510: break;
511:
1.7 schwarze 512: /*
513: * If we find a record, see if it has already evaluated
514: * to true. If it has, great, just keep going. If not,
515: * try to evaluate it now and continue anyway.
516: */
517:
1.12 schwarze 518: if (leaf >= 0 && rs[leaf].res.rec == vb.rec) {
1.7 schwarze 519: if (0 == rs[leaf].matched)
1.12 schwarze 520: exprexec(expr, buf, vb.mask, &rs[leaf]);
1.1 schwarze 521: continue;
1.4 schwarze 522: }
1.1 schwarze 523:
524: /*
1.7 schwarze 525: * We have a new file to examine.
526: * Extract the manpage's metadata from the index
527: * database, then begin partial evaluation.
1.1 schwarze 528: */
529:
1.12 schwarze 530: key.data = &vb.rec;
1.1 schwarze 531: key.size = sizeof(recno_t);
532:
533: if (0 != (*idx->get)(idx, &key, &val, 0))
1.8 schwarze 534: break;
1.1 schwarze 535:
1.7 schwarze 536: r.lhs = r.rhs = -1;
1.8 schwarze 537: if ( ! index_read(&key, &val, vol, mc, &r))
538: break;
1.1 schwarze 539:
1.7 schwarze 540: /* XXX: this should be elsewhere, I guess? */
1.8 schwarze 541:
1.7 schwarze 542: if (opts->cat && strcasecmp(opts->cat, r.res.cat))
1.1 schwarze 543: continue;
1.14 schwarze 544:
545: if (opts->arch && *r.res.arch)
546: if (strcasecmp(opts->arch, r.res.arch))
547: continue;
1.1 schwarze 548:
1.7 schwarze 549: tree->node = rs = mandoc_realloc
550: (rs, (tree->len + 1) * sizeof(struct rec));
1.1 schwarze 551:
1.7 schwarze 552: memcpy(&rs[tree->len], &r, sizeof(struct rec));
1.14 schwarze 553: memset(&r, 0, sizeof(struct rec));
1.8 schwarze 554: rs[tree->len].matches =
555: mandoc_calloc(terms, sizeof(int));
1.4 schwarze 556:
1.12 schwarze 557: exprexec(expr, buf, vb.mask, &rs[tree->len]);
1.1 schwarze 558:
559: /* Append to our tree. */
560:
561: if (leaf >= 0) {
1.12 schwarze 562: if (vb.rec > rs[leaf].res.rec)
1.7 schwarze 563: rs[leaf].rhs = tree->len;
1.1 schwarze 564: else
1.7 schwarze 565: rs[leaf].lhs = tree->len;
1.1 schwarze 566: } else
1.5 schwarze 567: root = tree->len;
1.8 schwarze 568:
1.5 schwarze 569: tree->len++;
1.1 schwarze 570: }
571:
1.8 schwarze 572: (*btree->close)(btree);
573: (*idx->close)(idx);
1.1 schwarze 574:
575: free(buf);
1.14 schwarze 576: recfree(&r);
1.8 schwarze 577: return(1 == ch);
1.1 schwarze 578: }
579:
1.4 schwarze 580: static void
581: recfree(struct rec *rec)
582: {
583:
1.7 schwarze 584: free(rec->res.file);
585: free(rec->res.cat);
586: free(rec->res.title);
587: free(rec->res.arch);
588: free(rec->res.desc);
589:
1.4 schwarze 590: free(rec->matches);
591: }
592:
1.10 schwarze 593: /*
594: * Compile a list of straight-up terms.
595: * The arguments are re-written into ~[[:<:]]term[[:>:]], or "term"
596: * surrounded by word boundaries, then pumped through exprterm().
597: * Terms are case-insensitive.
598: * This emulates whatis(1) behaviour.
599: */
600: struct expr *
601: termcomp(int argc, char *argv[], size_t *tt)
602: {
603: char *buf;
604: int pos;
605: struct expr *e, *next;
606: size_t sz;
607:
608: buf = NULL;
609: e = NULL;
610: *tt = 0;
611:
612: for (pos = argc - 1; pos >= 0; pos--) {
613: sz = strlen(argv[pos]) + 18;
614: buf = mandoc_realloc(buf, sz);
615: strlcpy(buf, "Nm~[[:<:]]", sz);
616: strlcat(buf, argv[pos], sz);
617: strlcat(buf, "[[:>:]]", sz);
618: if (NULL == (next = exprterm(buf, 0))) {
619: free(buf);
620: exprfree(e);
621: return(NULL);
622: }
623: next->next = e;
624: e = next;
625: (*tt)++;
626: }
627:
628: free(buf);
629: return(e);
630: }
631:
632: /*
633: * Compile a sequence of logical expressions.
634: * See apropos.1 for a grammar of this sequence.
635: */
1.1 schwarze 636: struct expr *
1.4 schwarze 637: exprcomp(int argc, char *argv[], size_t *tt)
638: {
1.7 schwarze 639: int pos, lvl;
640: struct expr *e;
641:
642: pos = lvl = 0;
643: *tt = 0;
644:
645: e = exprexpr(argc, argv, &pos, &lvl, tt);
646:
647: if (0 == lvl && pos >= argc)
648: return(e);
649:
650: exprfree(e);
651: return(NULL);
652: }
653:
654: /*
655: * Compile an array of tokens into an expression.
656: * An informal expression grammar is defined in apropos(1).
657: * Return NULL if we fail doing so. All memory will be cleaned up.
658: * Return the root of the expression sequence if alright.
659: */
660: static struct expr *
661: exprexpr(int argc, char *argv[], int *pos, int *lvl, size_t *tt)
662: {
1.4 schwarze 663: struct expr *e, *first, *next;
1.7 schwarze 664: int log;
1.4 schwarze 665:
666: first = next = NULL;
667:
1.7 schwarze 668: for ( ; *pos < argc; (*pos)++) {
1.4 schwarze 669: e = next;
1.7 schwarze 670:
671: /*
672: * Close out a subexpression.
673: */
674:
675: if (NULL != e && 0 == strcmp(")", argv[*pos])) {
676: if (--(*lvl) < 0)
677: goto err;
678: break;
679: }
680:
681: /*
682: * Small note: if we're just starting, don't let "-a"
683: * and "-o" be considered logical operators: they're
684: * just tokens unless pairwise joining, in which case we
685: * record their existence (or assume "OR").
686: */
1.4 schwarze 687: log = 0;
688:
1.7 schwarze 689: if (NULL != e && 0 == strcmp("-a", argv[*pos]))
1.8 schwarze 690: log = 1;
1.7 schwarze 691: else if (NULL != e && 0 == strcmp("-o", argv[*pos]))
1.4 schwarze 692: log = 2;
693:
1.7 schwarze 694: if (log > 0 && ++(*pos) >= argc)
1.4 schwarze 695: goto err;
696:
1.7 schwarze 697: /*
698: * Now we parse the term part. This can begin with
699: * "-i", in which case the expression is case
700: * insensitive.
701: */
702:
703: if (0 == strcmp("(", argv[*pos])) {
704: ++(*pos);
705: ++(*lvl);
706: next = mandoc_calloc(1, sizeof(struct expr));
707: next->subexpr = exprexpr(argc, argv, pos, lvl, tt);
708: if (NULL == next->subexpr) {
709: free(next);
710: next = NULL;
711: }
712: } else if (0 == strcmp("-i", argv[*pos])) {
713: if (++(*pos) >= argc)
1.4 schwarze 714: goto err;
1.7 schwarze 715: next = exprterm(argv[*pos], 0);
1.4 schwarze 716: } else
1.7 schwarze 717: next = exprterm(argv[*pos], 1);
1.4 schwarze 718:
719: if (NULL == next)
720: goto err;
721:
1.7 schwarze 722: next->and = log == 1;
1.4 schwarze 723: next->index = (int)(*tt)++;
724:
1.7 schwarze 725: /* Append to our chain of expressions. */
726:
1.4 schwarze 727: if (NULL == first) {
728: assert(NULL == e);
729: first = next;
730: } else {
731: assert(NULL != e);
732: e->next = next;
733: }
734: }
735:
736: return(first);
737: err:
738: exprfree(first);
739: return(NULL);
740: }
741:
1.7 schwarze 742: /*
743: * Parse a terminal expression with the grammar as defined in
744: * apropos(1).
745: * Return NULL if we fail the parse.
746: */
1.4 schwarze 747: static struct expr *
1.7 schwarze 748: exprterm(char *buf, int cs)
1.1 schwarze 749: {
1.4 schwarze 750: struct expr e;
1.1 schwarze 751: struct expr *p;
1.3 schwarze 752: char *key;
1.4 schwarze 753: int i;
1.1 schwarze 754:
1.4 schwarze 755: memset(&e, 0, sizeof(struct expr));
1.1 schwarze 756:
1.7 schwarze 757: /* Choose regex or substring match. */
1.3 schwarze 758:
1.4 schwarze 759: if (NULL == (e.v = strpbrk(buf, "=~"))) {
1.3 schwarze 760: e.regex = 0;
1.4 schwarze 761: e.v = buf;
1.3 schwarze 762: } else {
763: e.regex = '~' == *e.v;
764: *e.v++ = '\0';
765: }
1.1 schwarze 766:
1.7 schwarze 767: /* Determine the record types to search for. */
1.3 schwarze 768:
769: e.mask = 0;
1.4 schwarze 770: if (buf < e.v) {
771: while (NULL != (key = strsep(&buf, ","))) {
1.3 schwarze 772: i = 0;
773: while (types[i].mask &&
1.7 schwarze 774: strcmp(types[i].name, key))
1.3 schwarze 775: i++;
776: e.mask |= types[i].mask;
777: }
778: }
779: if (0 == e.mask)
780: e.mask = TYPE_Nm | TYPE_Nd;
1.1 schwarze 781:
1.4 schwarze 782: if (e.regex) {
1.10 schwarze 783: i = REG_EXTENDED | REG_NOSUB | (cs ? 0 : REG_ICASE);
1.4 schwarze 784: if (regcomp(&e.re, e.v, i))
785: return(NULL);
786: }
1.1 schwarze 787:
1.3 schwarze 788: e.v = mandoc_strdup(e.v);
1.1 schwarze 789:
790: p = mandoc_calloc(1, sizeof(struct expr));
791: memcpy(p, &e, sizeof(struct expr));
792: return(p);
793: }
794:
795: void
796: exprfree(struct expr *p)
797: {
1.4 schwarze 798: struct expr *pp;
1.8 schwarze 799:
1.4 schwarze 800: while (NULL != p) {
1.7 schwarze 801: if (p->subexpr)
802: exprfree(p->subexpr);
1.4 schwarze 803: if (p->regex)
804: regfree(&p->re);
805: free(p->v);
806: pp = p->next;
807: free(p);
808: p = pp;
809: }
810: }
1.1 schwarze 811:
1.4 schwarze 812: static int
1.8 schwarze 813: exprmark(const struct expr *p, const char *cp,
814: uint64_t mask, int *ms)
1.4 schwarze 815: {
1.1 schwarze 816:
1.7 schwarze 817: for ( ; p; p = p->next) {
818: if (p->subexpr) {
819: if (exprmark(p->subexpr, cp, mask, ms))
820: return(1);
821: continue;
822: } else if ( ! (mask & p->mask))
1.4 schwarze 823: continue;
1.7 schwarze 824:
1.4 schwarze 825: if (p->regex) {
1.7 schwarze 826: if (regexec(&p->re, cp, 0, NULL, 0))
827: continue;
1.11 schwarze 828: } else if (NULL == strcasestr(cp, p->v))
829: continue;
1.7 schwarze 830:
831: if (NULL == ms)
1.4 schwarze 832: return(1);
1.7 schwarze 833: else
834: ms[p->index] = 1;
1.4 schwarze 835: }
1.8 schwarze 836:
837: return(0);
1.7 schwarze 838: }
839:
840: static int
841: expreval(const struct expr *p, int *ms)
842: {
843: int match;
844:
845: /*
846: * AND has precedence over OR. Analysis is left-right, though
847: * it doesn't matter because there are no side-effects.
848: * Thus, step through pairwise ANDs and accumulate their Boolean
849: * evaluation. If we encounter a single true AND collection or
850: * standalone term, the whole expression is true (by definition
851: * of OR).
852: */
853:
854: for (match = 0; p && ! match; p = p->next) {
855: /* Evaluate a subexpression, if applicable. */
856: if (p->subexpr && ! ms[p->index])
857: ms[p->index] = expreval(p->subexpr, ms);
858:
859: match = ms[p->index];
860: for ( ; p->next && p->next->and; p = p->next) {
861: /* Evaluate a subexpression, if applicable. */
862: if (p->next->subexpr && ! ms[p->next->index])
863: ms[p->next->index] =
864: expreval(p->next->subexpr, ms);
865: match = match && ms[p->next->index];
866: }
867: }
868:
869: return(match);
1.1 schwarze 870: }
871:
1.4 schwarze 872: /*
873: * First, update the array of terms for which this expression evaluates
874: * to true.
875: * Second, logically evaluate all terms over the updated array of truth
876: * values.
877: * If this evaluates to true, mark the expression as satisfied.
878: */
879: static void
1.8 schwarze 880: exprexec(const struct expr *e, const char *cp,
881: uint64_t mask, struct rec *r)
1.1 schwarze 882: {
883:
1.7 schwarze 884: assert(0 == r->matched);
885: exprmark(e, cp, mask, r->matches);
886: r->matched = expreval(e, r->matches);
1.1 schwarze 887: }