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