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