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