Annotation of mandoc/apropos_db.c, Revision 1.32
1.32 ! kristaps 1: /* $Id: apropos_db.c,v 1.31 2012/03/24 01:46:25 kristaps 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
40: # include <db.h>
41: #endif
42:
1.2 schwarze 43: #include "mandocdb.h"
1.1 schwarze 44: #include "apropos_db.h"
45: #include "mandoc.h"
46:
1.30 kristaps 47: #define RESFREE(_x) \
48: do { \
49: free((_x)->file); \
50: free((_x)->cat); \
51: free((_x)->title); \
52: free((_x)->arch); \
53: free((_x)->desc); \
54: free((_x)->matches); \
55: } while (/*CONSTCOND*/0)
1.5 kristaps 56:
1.1 schwarze 57: struct expr {
1.5 kristaps 58: int regex; /* is regex? */
59: int index; /* index in match array */
1.6 kristaps 60: uint64_t mask; /* type-mask */
1.5 kristaps 61: int and; /* is rhs of logical AND? */
62: char *v; /* search value */
63: regex_t re; /* compiled re, if regex */
64: struct expr *next; /* next in sequence */
65: struct expr *subexpr;
1.1 schwarze 66: };
67:
68: struct type {
1.6 kristaps 69: uint64_t mask;
1.1 schwarze 70: const char *name;
71: };
72:
1.8 kristaps 73: struct rectree {
1.30 kristaps 74: struct res *node; /* record array for dir tree */
1.8 kristaps 75: int len; /* length of record array */
76: };
77:
1.1 schwarze 78: static const struct type types[] = {
1.7 kristaps 79: { TYPE_An, "An" },
80: { TYPE_Ar, "Ar" },
81: { TYPE_At, "At" },
82: { TYPE_Bsx, "Bsx" },
83: { TYPE_Bx, "Bx" },
84: { TYPE_Cd, "Cd" },
85: { TYPE_Cm, "Cm" },
86: { TYPE_Dv, "Dv" },
87: { TYPE_Dx, "Dx" },
88: { TYPE_Em, "Em" },
89: { TYPE_Er, "Er" },
90: { TYPE_Ev, "Ev" },
91: { TYPE_Fa, "Fa" },
92: { TYPE_Fl, "Fl" },
93: { TYPE_Fn, "Fn" },
94: { TYPE_Fn, "Fo" },
95: { TYPE_Ft, "Ft" },
96: { TYPE_Fx, "Fx" },
97: { TYPE_Ic, "Ic" },
98: { TYPE_In, "In" },
99: { TYPE_Lb, "Lb" },
100: { TYPE_Li, "Li" },
101: { TYPE_Lk, "Lk" },
102: { TYPE_Ms, "Ms" },
103: { TYPE_Mt, "Mt" },
104: { TYPE_Nd, "Nd" },
105: { TYPE_Nm, "Nm" },
106: { TYPE_Nx, "Nx" },
107: { TYPE_Ox, "Ox" },
108: { TYPE_Pa, "Pa" },
109: { TYPE_Rs, "Rs" },
110: { TYPE_Sh, "Sh" },
111: { TYPE_Ss, "Ss" },
112: { TYPE_St, "St" },
113: { TYPE_Sy, "Sy" },
114: { TYPE_Tn, "Tn" },
115: { TYPE_Va, "Va" },
116: { TYPE_Va, "Vt" },
117: { TYPE_Xr, "Xr" },
1.25 kristaps 118: { UINT64_MAX, "any" },
1.1 schwarze 119: { 0, NULL }
120: };
121:
122: static DB *btree_open(void);
1.17 kristaps 123: static int btree_read(const DBT *, const DBT *,
1.28 schwarze 124: const struct mchars *,
125: uint64_t *, recno_t *, char **);
1.5 kristaps 126: static int expreval(const struct expr *, int *);
1.12 schwarze 127: static void exprexec(const struct expr *,
1.30 kristaps 128: const char *, uint64_t, struct res *);
1.12 schwarze 129: static int exprmark(const struct expr *,
1.6 kristaps 130: const char *, uint64_t, int *);
1.5 kristaps 131: static struct expr *exprexpr(int, char *[], int *, int *, size_t *);
132: static struct expr *exprterm(char *, int);
1.1 schwarze 133: static DB *index_open(void);
1.11 kristaps 134: static int index_read(const DBT *, const DBT *, int,
1.30 kristaps 135: const struct mchars *, struct res *);
1.1 schwarze 136: static void norm_string(const char *,
137: const struct mchars *, char **);
138: static size_t norm_utf8(unsigned int, char[7]);
1.8 kristaps 139: static int single_search(struct rectree *, const struct opts *,
140: const struct expr *, size_t terms,
1.11 kristaps 141: struct mchars *, int);
1.1 schwarze 142:
143: /*
144: * Open the keyword mandoc-db database.
145: */
146: static DB *
147: btree_open(void)
148: {
149: BTREEINFO info;
150: DB *db;
151:
152: memset(&info, 0, sizeof(BTREEINFO));
1.29 kristaps 153: info.lorder = 4321;
1.1 schwarze 154: info.flags = R_DUP;
155:
1.2 schwarze 156: db = dbopen(MANDOC_DB, O_RDONLY, 0, DB_BTREE, &info);
1.12 schwarze 157: if (NULL != db)
1.1 schwarze 158: return(db);
159:
160: return(NULL);
161: }
162:
163: /*
164: * Read a keyword from the database and normalise it.
165: * Return 0 if the database is insane, else 1.
166: */
167: static int
1.28 schwarze 168: btree_read(const DBT *k, const DBT *v, const struct mchars *mc,
169: uint64_t *mask, recno_t *rec, char **buf)
1.1 schwarze 170: {
1.28 schwarze 171: uint64_t vbuf[2];
1.1 schwarze 172:
1.17 kristaps 173: /* Are our sizes sane? */
1.28 schwarze 174: if (k->size < 2 || sizeof(vbuf) != v->size)
1.17 kristaps 175: return(0);
1.6 kristaps 176:
1.17 kristaps 177: /* Is our string nil-terminated? */
178: if ('\0' != ((const char *)k->data)[(int)k->size - 1])
1.1 schwarze 179: return(0);
180:
1.17 kristaps 181: norm_string((const char *)k->data, mc, buf);
1.28 schwarze 182: memcpy(vbuf, v->data, v->size);
183: *mask = betoh64(vbuf[0]);
184: *rec = betoh64(vbuf[1]);
1.1 schwarze 185: return(1);
186: }
187:
188: /*
189: * Take a Unicode codepoint and produce its UTF-8 encoding.
190: * This isn't the best way to do this, but it works.
1.12 schwarze 191: * The magic numbers are from the UTF-8 packaging.
1.1 schwarze 192: * They're not as scary as they seem: read the UTF-8 spec for details.
193: */
194: static size_t
195: norm_utf8(unsigned int cp, char out[7])
196: {
1.26 kristaps 197: int rc;
1.1 schwarze 198:
199: rc = 0;
200:
201: if (cp <= 0x0000007F) {
202: rc = 1;
203: out[0] = (char)cp;
204: } else if (cp <= 0x000007FF) {
205: rc = 2;
206: out[0] = (cp >> 6 & 31) | 192;
207: out[1] = (cp & 63) | 128;
208: } else if (cp <= 0x0000FFFF) {
209: rc = 3;
210: out[0] = (cp >> 12 & 15) | 224;
211: out[1] = (cp >> 6 & 63) | 128;
212: out[2] = (cp & 63) | 128;
213: } else if (cp <= 0x001FFFFF) {
214: rc = 4;
215: out[0] = (cp >> 18 & 7) | 240;
216: out[1] = (cp >> 12 & 63) | 128;
217: out[2] = (cp >> 6 & 63) | 128;
218: out[3] = (cp & 63) | 128;
219: } else if (cp <= 0x03FFFFFF) {
220: rc = 5;
221: out[0] = (cp >> 24 & 3) | 248;
222: out[1] = (cp >> 18 & 63) | 128;
223: out[2] = (cp >> 12 & 63) | 128;
224: out[3] = (cp >> 6 & 63) | 128;
225: out[4] = (cp & 63) | 128;
226: } else if (cp <= 0x7FFFFFFF) {
227: rc = 6;
228: out[0] = (cp >> 30 & 1) | 252;
229: out[1] = (cp >> 24 & 63) | 128;
230: out[2] = (cp >> 18 & 63) | 128;
231: out[3] = (cp >> 12 & 63) | 128;
232: out[4] = (cp >> 6 & 63) | 128;
233: out[5] = (cp & 63) | 128;
234: } else
235: return(0);
236:
237: out[rc] = '\0';
1.26 kristaps 238: return((size_t)rc);
1.1 schwarze 239: }
240:
241: /*
242: * Normalise strings from the index and database.
243: * These strings are escaped as defined by mandoc_char(7) along with
244: * other goop in mandoc.h (e.g., soft hyphens).
245: * This function normalises these into a nice UTF-8 string.
246: * Returns 0 if the database is fucked.
247: */
248: static void
249: norm_string(const char *val, const struct mchars *mc, char **buf)
250: {
251: size_t sz, bsz;
252: char utfbuf[7];
253: const char *seq, *cpp;
254: int len, u, pos;
255: enum mandoc_esc esc;
1.12 schwarze 256: static const char res[] = { '\\', '\t',
1.1 schwarze 257: ASCII_NBRSP, ASCII_HYPH, '\0' };
258:
259: /* Pre-allocate by the length of the input */
260:
261: bsz = strlen(val) + 1;
262: *buf = mandoc_realloc(*buf, bsz);
263: pos = 0;
264:
265: while ('\0' != *val) {
266: /*
267: * Halt on the first escape sequence.
268: * This also halts on the end of string, in which case
269: * we just copy, fallthrough, and exit the loop.
270: */
271: if ((sz = strcspn(val, res)) > 0) {
272: memcpy(&(*buf)[pos], val, sz);
273: pos += (int)sz;
274: val += (int)sz;
275: }
276:
277: if (ASCII_HYPH == *val) {
278: (*buf)[pos++] = '-';
279: val++;
280: continue;
281: } else if ('\t' == *val || ASCII_NBRSP == *val) {
282: (*buf)[pos++] = ' ';
283: val++;
284: continue;
285: } else if ('\\' != *val)
286: break;
287:
288: /* Read past the slash. */
289:
290: val++;
291: u = 0;
292:
293: /*
294: * Parse the escape sequence and see if it's a
295: * predefined character or special character.
296: */
297:
298: esc = mandoc_escape(&val, &seq, &len);
299: if (ESCAPE_ERROR == esc)
300: break;
301:
1.12 schwarze 302: /*
1.1 schwarze 303: * XXX - this just does UTF-8, but we need to know
304: * beforehand whether we should do text substitution.
305: */
306:
307: switch (esc) {
308: case (ESCAPE_SPECIAL):
309: if (0 != (u = mchars_spec2cp(mc, seq, len)))
310: break;
311: /* FALLTHROUGH */
312: default:
313: continue;
314: }
315:
316: /*
317: * If we have a Unicode codepoint, try to convert that
318: * to a UTF-8 byte string.
319: */
320:
321: cpp = utfbuf;
322: if (0 == (sz = norm_utf8(u, utfbuf)))
323: continue;
324:
325: /* Copy the rendered glyph into the stream. */
326:
327: sz = strlen(cpp);
328: bsz += sz;
329:
330: *buf = mandoc_realloc(*buf, bsz);
331:
332: memcpy(&(*buf)[pos], cpp, sz);
333: pos += (int)sz;
334: }
335:
336: (*buf)[pos] = '\0';
337: }
338:
339: /*
340: * Open the filename-index mandoc-db database.
341: * Returns NULL if opening failed.
342: */
343: static DB *
344: index_open(void)
345: {
346: DB *db;
347:
1.2 schwarze 348: db = dbopen(MANDOC_IDX, O_RDONLY, 0, DB_RECNO, NULL);
1.1 schwarze 349: if (NULL != db)
350: return(db);
351:
352: return(NULL);
353: }
354:
355: /*
356: * Safely unpack from an index file record into the structure.
357: * Returns 1 if an entry was unpacked, 0 if the database is insane.
358: */
359: static int
1.11 kristaps 360: index_read(const DBT *key, const DBT *val, int index,
1.30 kristaps 361: const struct mchars *mc, struct res *rec)
1.1 schwarze 362: {
363: size_t left;
364: char *np, *cp;
1.24 kristaps 365: char type;
1.1 schwarze 366:
367: #define INDEX_BREAD(_dst) \
368: do { \
369: if (NULL == (np = memchr(cp, '\0', left))) \
370: return(0); \
371: norm_string(cp, mc, &(_dst)); \
372: left -= (np - cp) + 1; \
373: cp = np + 1; \
374: } while (/* CONSTCOND */ 0)
375:
1.24 kristaps 376: if (0 == (left = val->size))
377: return(0);
1.1 schwarze 378:
1.24 kristaps 379: cp = val->data;
1.27 schwarze 380: assert(sizeof(recno_t) == key->size);
1.30 kristaps 381: memcpy(&rec->rec, key->data, key->size);
382: rec->volume = index;
1.1 schwarze 383:
1.24 kristaps 384: if ('d' == (type = *cp++))
1.30 kristaps 385: rec->type = RESTYPE_MDOC;
1.24 kristaps 386: else if ('a' == type)
1.30 kristaps 387: rec->type = RESTYPE_MAN;
1.24 kristaps 388: else if ('c' == type)
1.30 kristaps 389: rec->type = RESTYPE_CAT;
1.24 kristaps 390: else
391: return(0);
392:
393: left--;
1.30 kristaps 394: INDEX_BREAD(rec->file);
395: INDEX_BREAD(rec->cat);
396: INDEX_BREAD(rec->title);
397: INDEX_BREAD(rec->arch);
398: INDEX_BREAD(rec->desc);
1.1 schwarze 399: return(1);
400: }
401:
402: /*
1.10 kristaps 403: * Search mandocdb databases in paths for expression "expr".
1.1 schwarze 404: * Filter out by "opts".
405: * Call "res" with the results, which may be zero.
1.5 kristaps 406: * Return 0 if there was a database error, else return 1.
1.1 schwarze 407: */
1.5 kristaps 408: int
1.10 kristaps 409: apropos_search(int pathsz, char **paths, const struct opts *opts,
1.12 schwarze 410: const struct expr *expr, size_t terms, void *arg,
1.30 kristaps 411: size_t *sz, struct res **resp,
1.5 kristaps 412: void (*res)(struct res *, size_t, void *))
1.1 schwarze 413: {
1.8 kristaps 414: struct rectree tree;
415: struct mchars *mc;
1.30 kristaps 416: int i, rc;
1.8 kristaps 417:
418: memset(&tree, 0, sizeof(struct rectree));
419:
1.10 kristaps 420: rc = 0;
1.8 kristaps 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