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