]>
git.cameronkatri.com Git - mandoc.git/blob - apropos_db.c
1 /* $Id: apropos_db.c,v 1.32 2012/03/25 00:48:47 kristaps Exp $ */
3 * Copyright (c) 2011, 2012 Kristaps Dzonsons <kristaps@bsd.lv>
4 * Copyright (c) 2011 Ingo Schwarze <schwarze@openbsd.org>
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.
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.
22 #include <sys/param.h>
33 #if defined(__linux__)
36 #elif defined(__APPLE__)
37 # include <libkern/OSByteOrder.h>
44 #include "apropos_db.h"
54 free((_x)->matches); \
55 } while (/*CONSTCOND*/0)
58 int regex
; /* is regex? */
59 int index
; /* index in match array */
60 uint64_t mask
; /* type-mask */
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 */
74 struct res
*node
; /* record array for dir tree */
75 int len
; /* length of record array */
78 static const struct type types
[] = {
118 { UINT64_MAX
, "any" },
122 static DB
*btree_open(void);
123 static int btree_read(const DBT
*, const DBT
*,
124 const struct mchars
*,
125 uint64_t *, recno_t
*, char **);
126 static int expreval(const struct expr
*, int *);
127 static void exprexec(const struct expr
*,
128 const char *, uint64_t, struct res
*);
129 static int exprmark(const struct expr
*,
130 const char *, uint64_t, int *);
131 static struct expr
*exprexpr(int, char *[], int *, int *, size_t *);
132 static struct expr
*exprterm(char *, int);
133 static DB
*index_open(void);
134 static int index_read(const DBT
*, const DBT
*, int,
135 const struct mchars
*, struct res
*);
136 static void norm_string(const char *,
137 const struct mchars
*, char **);
138 static size_t norm_utf8(unsigned int, char[7]);
139 static int single_search(struct rectree
*, const struct opts
*,
140 const struct expr
*, size_t terms
,
141 struct mchars
*, int);
144 * Open the keyword mandoc-db database.
152 memset(&info
, 0, sizeof(BTREEINFO
));
156 db
= dbopen(MANDOC_DB
, O_RDONLY
, 0, DB_BTREE
, &info
);
164 * Read a keyword from the database and normalise it.
165 * Return 0 if the database is insane, else 1.
168 btree_read(const DBT
*k
, const DBT
*v
, const struct mchars
*mc
,
169 uint64_t *mask
, recno_t
*rec
, char **buf
)
173 /* Are our sizes sane? */
174 if (k
->size
< 2 || sizeof(vbuf
) != v
->size
)
177 /* Is our string nil-terminated? */
178 if ('\0' != ((const char *)k
->data
)[(int)k
->size
- 1])
181 norm_string((const char *)k
->data
, mc
, buf
);
182 memcpy(vbuf
, v
->data
, v
->size
);
183 *mask
= betoh64(vbuf
[0]);
184 *rec
= betoh64(vbuf
[1]);
189 * Take a Unicode codepoint and produce its UTF-8 encoding.
190 * This isn't the best way to do this, but it works.
191 * The magic numbers are from the UTF-8 packaging.
192 * They're not as scary as they seem: read the UTF-8 spec for details.
195 norm_utf8(unsigned int cp
, char out
[7])
201 if (cp
<= 0x0000007F) {
204 } else if (cp
<= 0x000007FF) {
206 out
[0] = (cp
>> 6 & 31) | 192;
207 out
[1] = (cp
& 63) | 128;
208 } else if (cp
<= 0x0000FFFF) {
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) {
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) {
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) {
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;
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.
249 norm_string(const char *val
, const struct mchars
*mc
, char **buf
)
253 const char *seq
, *cpp
;
256 static const char res
[] = { '\\', '\t',
257 ASCII_NBRSP
, ASCII_HYPH
, '\0' };
259 /* Pre-allocate by the length of the input */
261 bsz
= strlen(val
) + 1;
262 *buf
= mandoc_realloc(*buf
, bsz
);
265 while ('\0' != *val
) {
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.
271 if ((sz
= strcspn(val
, res
)) > 0) {
272 memcpy(&(*buf
)[pos
], val
, sz
);
277 if (ASCII_HYPH
== *val
) {
281 } else if ('\t' == *val
|| ASCII_NBRSP
== *val
) {
285 } else if ('\\' != *val
)
288 /* Read past the slash. */
294 * Parse the escape sequence and see if it's a
295 * predefined character or special character.
298 esc
= mandoc_escape(&val
, &seq
, &len
);
299 if (ESCAPE_ERROR
== esc
)
303 * XXX - this just does UTF-8, but we need to know
304 * beforehand whether we should do text substitution.
308 case (ESCAPE_SPECIAL
):
309 if (0 != (u
= mchars_spec2cp(mc
, seq
, len
)))
317 * If we have a Unicode codepoint, try to convert that
318 * to a UTF-8 byte string.
322 if (0 == (sz
= norm_utf8(u
, utfbuf
)))
325 /* Copy the rendered glyph into the stream. */
330 *buf
= mandoc_realloc(*buf
, bsz
);
332 memcpy(&(*buf
)[pos
], cpp
, sz
);
340 * Open the filename-index mandoc-db database.
341 * Returns NULL if opening failed.
348 db
= dbopen(MANDOC_IDX
, O_RDONLY
, 0, DB_RECNO
, NULL
);
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.
360 index_read(const DBT
*key
, const DBT
*val
, int index
,
361 const struct mchars
*mc
, struct res
*rec
)
367 #define INDEX_BREAD(_dst) \
369 if (NULL == (np = memchr(cp, '\0', left))) \
371 norm_string(cp, mc, &(_dst)); \
372 left -= (np - cp) + 1; \
374 } while (/* CONSTCOND */ 0)
376 if (0 == (left
= val
->size
))
380 assert(sizeof(recno_t
) == key
->size
);
381 memcpy(&rec
->rec
, key
->data
, key
->size
);
384 if ('d' == (type
= *cp
++))
385 rec
->type
= RESTYPE_MDOC
;
386 else if ('a' == type
)
387 rec
->type
= RESTYPE_MAN
;
388 else if ('c' == type
)
389 rec
->type
= RESTYPE_CAT
;
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
);
403 * Search mandocdb databases in paths for expression "expr".
404 * Filter out by "opts".
405 * Call "res" with the results, which may be zero.
406 * Return 0 if there was a database error, else return 1.
409 apropos_search(int pathsz
, char **paths
, const struct opts
*opts
,
410 const struct expr
*expr
, size_t terms
, void *arg
,
411 size_t *sz
, struct res
**resp
,
412 void (*res
)(struct res
*, size_t, void *))
418 memset(&tree
, 0, sizeof(struct rectree
));
426 * Main loop. Change into the directory containing manpage
427 * databases. Run our expession over each database in the set.
430 for (i
= 0; i
< pathsz
; i
++) {
431 assert('/' == paths
[i
][0]);
434 if (single_search(&tree
, opts
, expr
, terms
, mc
, i
))
437 resfree(tree
.node
, tree
.len
);
442 (*res
)(tree
.node
, tree
.len
, arg
);
450 single_search(struct rectree
*tree
, const struct opts
*opts
,
451 const struct expr
*expr
, size_t terms
,
452 struct mchars
*mc
, int vol
)
470 memset(&r
, 0, sizeof(struct res
));
472 if (NULL
== (btree
= btree_open()))
475 if (NULL
== (idx
= index_open())) {
476 (*btree
->close
)(btree
);
480 while (0 == (ch
= (*btree
->seq
)(btree
, &key
, &val
, R_NEXT
))) {
481 if ( ! btree_read(&key
, &val
, mc
, &mask
, &rec
, &buf
))
485 * See if this keyword record matches any of the
486 * expressions we have stored.
488 if ( ! exprmark(expr
, buf
, mask
, NULL
))
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.
497 for (leaf
= root
; leaf
>= 0; )
498 if (rec
> rs
[leaf
].rec
&&
501 else if (rec
< rs
[leaf
].rec
&&
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.
513 if (leaf
>= 0 && rs
[leaf
].rec
== rec
) {
514 if (0 == rs
[leaf
].matched
)
515 exprexec(expr
, buf
, mask
, &rs
[leaf
]);
520 * We have a new file to examine.
521 * Extract the manpage's metadata from the index
522 * database, then begin partial evaluation.
526 key
.size
= sizeof(recno_t
);
528 if (0 != (*idx
->get
)(idx
, &key
, &val
, 0))
532 if ( ! index_read(&key
, &val
, vol
, mc
, &r
))
535 /* XXX: this should be elsewhere, I guess? */
537 if (opts
->cat
&& strcasecmp(opts
->cat
, r
.cat
))
540 if (opts
->arch
&& *r
.arch
)
541 if (strcasecmp(opts
->arch
, r
.arch
))
544 tree
->node
= rs
= mandoc_realloc
545 (rs
, (tree
->len
+ 1) * sizeof(struct res
));
547 memcpy(&rs
[tree
->len
], &r
, sizeof(struct res
));
548 memset(&r
, 0, sizeof(struct res
));
549 rs
[tree
->len
].matches
=
550 mandoc_calloc(terms
, sizeof(int));
552 exprexec(expr
, buf
, mask
, &rs
[tree
->len
]);
554 /* Append to our tree. */
557 if (rec
> rs
[leaf
].rec
)
558 rs
[leaf
].rhs
= tree
->len
;
560 rs
[leaf
].lhs
= tree
->len
;
567 (*btree
->close
)(btree
);
576 resfree(struct res
*rec
, size_t sz
)
580 for (i
= 0; i
< sz
; i
++)
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.
593 termcomp(int argc
, char *argv
[], size_t *tt
)
597 struct expr
*e
, *next
;
604 for (pos
= argc
- 1; pos
>= 0; pos
--) {
605 sz
= strlen(argv
[pos
]) + 18;
606 buf
= mandoc_realloc(buf
, sz
);
607 strlcpy(buf
, "Nm~[[:<:]]", sz
);
608 strlcat(buf
, argv
[pos
], sz
);
609 strlcat(buf
, "[[:>:]]", sz
);
610 if (NULL
== (next
= exprterm(buf
, 0))) {
625 * Compile a sequence of logical expressions.
626 * See apropos.1 for a grammar of this sequence.
629 exprcomp(int argc
, char *argv
[], size_t *tt
)
637 e
= exprexpr(argc
, argv
, &pos
, &lvl
, tt
);
639 if (0 == lvl
&& pos
>= argc
)
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.
653 exprexpr(int argc
, char *argv
[], int *pos
, int *lvl
, size_t *tt
)
655 struct expr
*e
, *first
, *next
;
660 for ( ; *pos
< argc
; (*pos
)++) {
664 * Close out a subexpression.
667 if (NULL
!= e
&& 0 == strcmp(")", argv
[*pos
])) {
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").
681 if (NULL
!= e
&& 0 == strcmp("-a", argv
[*pos
]))
683 else if (NULL
!= e
&& 0 == strcmp("-o", argv
[*pos
]))
686 if (log
> 0 && ++(*pos
) >= argc
)
690 * Now we parse the term part. This can begin with
691 * "-i", in which case the expression is case
695 if (0 == strcmp("(", argv
[*pos
])) {
698 next
= mandoc_calloc(1, sizeof(struct expr
));
699 next
->subexpr
= exprexpr(argc
, argv
, pos
, lvl
, tt
);
700 if (NULL
== next
->subexpr
) {
704 } else if (0 == strcmp("-i", argv
[*pos
])) {
705 if (++(*pos
) >= argc
)
707 next
= exprterm(argv
[*pos
], 0);
709 next
= exprterm(argv
[*pos
], 1);
714 next
->and = log
== 1;
715 next
->index
= (int)(*tt
)++;
717 /* Append to our chain of expressions. */
735 * Parse a terminal expression with the grammar as defined in
737 * Return NULL if we fail the parse.
740 exprterm(char *buf
, int cs
)
747 memset(&e
, 0, sizeof(struct expr
));
749 /* Choose regex or substring match. */
751 if (NULL
== (e
.v
= strpbrk(buf
, "=~"))) {
755 e
.regex
= '~' == *e
.v
;
759 /* Determine the record types to search for. */
763 while (NULL
!= (key
= strsep(&buf
, ","))) {
765 while (types
[i
].mask
&&
766 strcmp(types
[i
].name
, key
))
768 e
.mask
|= types
[i
].mask
;
772 e
.mask
= TYPE_Nm
| TYPE_Nd
;
775 i
= REG_EXTENDED
| REG_NOSUB
| (cs
? 0 : REG_ICASE
);
776 if (regcomp(&e
.re
, e
.v
, i
))
780 e
.v
= mandoc_strdup(e
.v
);
782 p
= mandoc_calloc(1, sizeof(struct expr
));
783 memcpy(p
, &e
, sizeof(struct expr
));
788 exprfree(struct expr
*p
)
794 exprfree(p
->subexpr
);
805 exprmark(const struct expr
*p
, const char *cp
,
806 uint64_t mask
, int *ms
)
809 for ( ; p
; p
= p
->next
) {
811 if (exprmark(p
->subexpr
, cp
, mask
, ms
))
814 } else if ( ! (mask
& p
->mask
))
818 if (regexec(&p
->re
, cp
, 0, NULL
, 0))
820 } else if (NULL
== strcasestr(cp
, p
->v
))
833 expreval(const struct expr
*p
, int *ms
)
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
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
);
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
])
856 expreval(p
->next
->subexpr
, ms
);
857 match
= match
&& ms
[p
->next
->index
];
865 * First, update the array of terms for which this expression evaluates
867 * Second, logically evaluate all terms over the updated array of truth
869 * If this evaluates to true, mark the expression as satisfied.
872 exprexec(const struct expr
*e
, const char *cp
,
873 uint64_t mask
, struct res
*r
)
876 assert(0 == r
->matched
);
877 exprmark(e
, cp
, mask
, r
->matches
);
878 r
->matched
= expreval(e
, r
->matches
);