]>
git.cameronkatri.com Git - mandoc.git/blob - apropos_db.c
1 /* $Id: apropos_db.c,v 1.28 2011/12/25 14:58:39 schwarze Exp $ */
3 * Copyright (c) 2011 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.
31 #if defined(__linux__)
34 #elif defined(__APPLE__)
35 # include <libkern/OSByteOrder.h>
42 #include "apropos_db.h"
46 struct res res
; /* resulting record info */
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.
55 int matched
; /* expression is true */
56 int *matches
; /* partial truth evaluations */
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 */
76 struct rec
*node
; /* record array for dir tree */
77 int len
; /* length of record array */
80 static const struct type types
[] = {
120 { UINT64_MAX
, "any" },
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);
147 * Open the keyword mandoc-db database.
155 memset(&info
, 0, sizeof(BTREEINFO
));
158 db
= dbopen(MANDOC_DB
, O_RDONLY
, 0, DB_BTREE
, &info
);
166 * Read a keyword from the database and normalise it.
167 * Return 0 if the database is insane, else 1.
170 btree_read(const DBT
*k
, const DBT
*v
, const struct mchars
*mc
,
171 uint64_t *mask
, recno_t
*rec
, char **buf
)
175 /* Are our sizes sane? */
176 if (k
->size
< 2 || sizeof(vbuf
) != v
->size
)
179 /* Is our string nil-terminated? */
180 if ('\0' != ((const char *)k
->data
)[(int)k
->size
- 1])
183 norm_string((const char *)k
->data
, mc
, buf
);
184 memcpy(vbuf
, v
->data
, v
->size
);
185 *mask
= betoh64(vbuf
[0]);
186 *rec
= betoh64(vbuf
[1]);
191 * Take a Unicode codepoint and produce its UTF-8 encoding.
192 * This isn't the best way to do this, but it works.
193 * The magic numbers are from the UTF-8 packaging.
194 * They're not as scary as they seem: read the UTF-8 spec for details.
197 norm_utf8(unsigned int cp
, char out
[7])
203 if (cp
<= 0x0000007F) {
206 } else if (cp
<= 0x000007FF) {
208 out
[0] = (cp
>> 6 & 31) | 192;
209 out
[1] = (cp
& 63) | 128;
210 } else if (cp
<= 0x0000FFFF) {
212 out
[0] = (cp
>> 12 & 15) | 224;
213 out
[1] = (cp
>> 6 & 63) | 128;
214 out
[2] = (cp
& 63) | 128;
215 } else if (cp
<= 0x001FFFFF) {
217 out
[0] = (cp
>> 18 & 7) | 240;
218 out
[1] = (cp
>> 12 & 63) | 128;
219 out
[2] = (cp
>> 6 & 63) | 128;
220 out
[3] = (cp
& 63) | 128;
221 } else if (cp
<= 0x03FFFFFF) {
223 out
[0] = (cp
>> 24 & 3) | 248;
224 out
[1] = (cp
>> 18 & 63) | 128;
225 out
[2] = (cp
>> 12 & 63) | 128;
226 out
[3] = (cp
>> 6 & 63) | 128;
227 out
[4] = (cp
& 63) | 128;
228 } else if (cp
<= 0x7FFFFFFF) {
230 out
[0] = (cp
>> 30 & 1) | 252;
231 out
[1] = (cp
>> 24 & 63) | 128;
232 out
[2] = (cp
>> 18 & 63) | 128;
233 out
[3] = (cp
>> 12 & 63) | 128;
234 out
[4] = (cp
>> 6 & 63) | 128;
235 out
[5] = (cp
& 63) | 128;
244 * Normalise strings from the index and database.
245 * These strings are escaped as defined by mandoc_char(7) along with
246 * other goop in mandoc.h (e.g., soft hyphens).
247 * This function normalises these into a nice UTF-8 string.
248 * Returns 0 if the database is fucked.
251 norm_string(const char *val
, const struct mchars
*mc
, char **buf
)
255 const char *seq
, *cpp
;
258 static const char res
[] = { '\\', '\t',
259 ASCII_NBRSP
, ASCII_HYPH
, '\0' };
261 /* Pre-allocate by the length of the input */
263 bsz
= strlen(val
) + 1;
264 *buf
= mandoc_realloc(*buf
, bsz
);
267 while ('\0' != *val
) {
269 * Halt on the first escape sequence.
270 * This also halts on the end of string, in which case
271 * we just copy, fallthrough, and exit the loop.
273 if ((sz
= strcspn(val
, res
)) > 0) {
274 memcpy(&(*buf
)[pos
], val
, sz
);
279 if (ASCII_HYPH
== *val
) {
283 } else if ('\t' == *val
|| ASCII_NBRSP
== *val
) {
287 } else if ('\\' != *val
)
290 /* Read past the slash. */
296 * Parse the escape sequence and see if it's a
297 * predefined character or special character.
300 esc
= mandoc_escape(&val
, &seq
, &len
);
301 if (ESCAPE_ERROR
== esc
)
305 * XXX - this just does UTF-8, but we need to know
306 * beforehand whether we should do text substitution.
310 case (ESCAPE_SPECIAL
):
311 if (0 != (u
= mchars_spec2cp(mc
, seq
, len
)))
319 * If we have a Unicode codepoint, try to convert that
320 * to a UTF-8 byte string.
324 if (0 == (sz
= norm_utf8(u
, utfbuf
)))
327 /* Copy the rendered glyph into the stream. */
332 *buf
= mandoc_realloc(*buf
, bsz
);
334 memcpy(&(*buf
)[pos
], cpp
, sz
);
342 * Open the filename-index mandoc-db database.
343 * Returns NULL if opening failed.
350 db
= dbopen(MANDOC_IDX
, O_RDONLY
, 0, DB_RECNO
, NULL
);
358 * Safely unpack from an index file record into the structure.
359 * Returns 1 if an entry was unpacked, 0 if the database is insane.
362 index_read(const DBT
*key
, const DBT
*val
, int index
,
363 const struct mchars
*mc
, struct rec
*rec
)
369 #define INDEX_BREAD(_dst) \
371 if (NULL == (np = memchr(cp, '\0', left))) \
373 norm_string(cp, mc, &(_dst)); \
374 left -= (np - cp) + 1; \
376 } while (/* CONSTCOND */ 0)
378 if (0 == (left
= val
->size
))
382 assert(sizeof(recno_t
) == key
->size
);
383 memcpy(&rec
->res
.rec
, key
->data
, key
->size
);
384 rec
->res
.volume
= index
;
386 if ('d' == (type
= *cp
++))
387 rec
->res
.type
= RESTYPE_MDOC
;
388 else if ('a' == type
)
389 rec
->res
.type
= RESTYPE_MAN
;
390 else if ('c' == type
)
391 rec
->res
.type
= RESTYPE_CAT
;
396 INDEX_BREAD(rec
->res
.file
);
397 INDEX_BREAD(rec
->res
.cat
);
398 INDEX_BREAD(rec
->res
.title
);
399 INDEX_BREAD(rec
->res
.arch
);
400 INDEX_BREAD(rec
->res
.desc
);
405 * Search mandocdb databases in paths for expression "expr".
406 * Filter out by "opts".
407 * Call "res" with the results, which may be zero.
408 * Return 0 if there was a database error, else return 1.
411 apropos_search(int pathsz
, char **paths
, const struct opts
*opts
,
412 const struct expr
*expr
, size_t terms
, void *arg
,
413 void (*res
)(struct res
*, size_t, void *))
420 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
++) {
433 if ( ! single_search(&tree
, opts
, expr
, terms
, mc
, i
))
438 * Count matching files, transfer to a "clean" array, then feed
439 * them to the output handler.
442 for (mlen
= i
= 0; i
< tree
.len
; i
++)
443 if (tree
.node
[i
].matched
)
446 ress
= mandoc_malloc(mlen
* sizeof(struct res
));
448 for (mlen
= i
= 0; i
< tree
.len
; i
++)
449 if (tree
.node
[i
].matched
)
450 memcpy(&ress
[mlen
++], &tree
.node
[i
].res
,
453 (*res
)(ress
, mlen
, arg
);
458 for (i
= 0; i
< tree
.len
; i
++)
459 recfree(&tree
.node
[i
]);
467 single_search(struct rectree
*tree
, const struct opts
*opts
,
468 const struct expr
*expr
, size_t terms
,
469 struct mchars
*mc
, int vol
)
487 memset(&r
, 0, sizeof(struct rec
));
489 if (NULL
== (btree
= btree_open()))
492 if (NULL
== (idx
= index_open())) {
493 (*btree
->close
)(btree
);
497 while (0 == (ch
= (*btree
->seq
)(btree
, &key
, &val
, R_NEXT
))) {
498 if ( ! btree_read(&key
, &val
, mc
, &mask
, &rec
, &buf
))
502 * See if this keyword record matches any of the
503 * expressions we have stored.
505 if ( ! exprmark(expr
, buf
, mask
, NULL
))
509 * O(log n) scan for prior records. Since a record
510 * number is unbounded, this has decent performance over
511 * a complex hash function.
514 for (leaf
= root
; leaf
>= 0; )
515 if (rec
> rs
[leaf
].res
.rec
&&
518 else if (rec
< rs
[leaf
].res
.rec
&&
525 * If we find a record, see if it has already evaluated
526 * to true. If it has, great, just keep going. If not,
527 * try to evaluate it now and continue anyway.
530 if (leaf
>= 0 && rs
[leaf
].res
.rec
== rec
) {
531 if (0 == rs
[leaf
].matched
)
532 exprexec(expr
, buf
, mask
, &rs
[leaf
]);
537 * We have a new file to examine.
538 * Extract the manpage's metadata from the index
539 * database, then begin partial evaluation.
543 key
.size
= sizeof(recno_t
);
545 if (0 != (*idx
->get
)(idx
, &key
, &val
, 0))
549 if ( ! index_read(&key
, &val
, vol
, mc
, &r
))
552 /* XXX: this should be elsewhere, I guess? */
554 if (opts
->cat
&& strcasecmp(opts
->cat
, r
.res
.cat
))
557 if (opts
->arch
&& *r
.res
.arch
)
558 if (strcasecmp(opts
->arch
, r
.res
.arch
))
561 tree
->node
= rs
= mandoc_realloc
562 (rs
, (tree
->len
+ 1) * sizeof(struct rec
));
564 memcpy(&rs
[tree
->len
], &r
, sizeof(struct rec
));
565 memset(&r
, 0, sizeof(struct rec
));
566 rs
[tree
->len
].matches
=
567 mandoc_calloc(terms
, sizeof(int));
569 exprexec(expr
, buf
, mask
, &rs
[tree
->len
]);
571 /* Append to our tree. */
574 if (rec
> rs
[leaf
].res
.rec
)
575 rs
[leaf
].rhs
= tree
->len
;
577 rs
[leaf
].lhs
= tree
->len
;
584 (*btree
->close
)(btree
);
593 recfree(struct rec
*rec
)
598 free(rec
->res
.title
);
606 * Compile a list of straight-up terms.
607 * The arguments are re-written into ~[[:<:]]term[[:>:]], or "term"
608 * surrounded by word boundaries, then pumped through exprterm().
609 * Terms are case-insensitive.
610 * This emulates whatis(1) behaviour.
613 termcomp(int argc
, char *argv
[], size_t *tt
)
617 struct expr
*e
, *next
;
624 for (pos
= argc
- 1; pos
>= 0; pos
--) {
625 sz
= strlen(argv
[pos
]) + 18;
626 buf
= mandoc_realloc(buf
, sz
);
627 strlcpy(buf
, "Nm~[[:<:]]", sz
);
628 strlcat(buf
, argv
[pos
], sz
);
629 strlcat(buf
, "[[:>:]]", sz
);
630 if (NULL
== (next
= exprterm(buf
, 0))) {
645 * Compile a sequence of logical expressions.
646 * See apropos.1 for a grammar of this sequence.
649 exprcomp(int argc
, char *argv
[], size_t *tt
)
657 e
= exprexpr(argc
, argv
, &pos
, &lvl
, tt
);
659 if (0 == lvl
&& pos
>= argc
)
667 * Compile an array of tokens into an expression.
668 * An informal expression grammar is defined in apropos(1).
669 * Return NULL if we fail doing so. All memory will be cleaned up.
670 * Return the root of the expression sequence if alright.
673 exprexpr(int argc
, char *argv
[], int *pos
, int *lvl
, size_t *tt
)
675 struct expr
*e
, *first
, *next
;
680 for ( ; *pos
< argc
; (*pos
)++) {
684 * Close out a subexpression.
687 if (NULL
!= e
&& 0 == strcmp(")", argv
[*pos
])) {
694 * Small note: if we're just starting, don't let "-a"
695 * and "-o" be considered logical operators: they're
696 * just tokens unless pairwise joining, in which case we
697 * record their existence (or assume "OR").
701 if (NULL
!= e
&& 0 == strcmp("-a", argv
[*pos
]))
703 else if (NULL
!= e
&& 0 == strcmp("-o", argv
[*pos
]))
706 if (log
> 0 && ++(*pos
) >= argc
)
710 * Now we parse the term part. This can begin with
711 * "-i", in which case the expression is case
715 if (0 == strcmp("(", argv
[*pos
])) {
718 next
= mandoc_calloc(1, sizeof(struct expr
));
719 next
->subexpr
= exprexpr(argc
, argv
, pos
, lvl
, tt
);
720 if (NULL
== next
->subexpr
) {
724 } else if (0 == strcmp("-i", argv
[*pos
])) {
725 if (++(*pos
) >= argc
)
727 next
= exprterm(argv
[*pos
], 0);
729 next
= exprterm(argv
[*pos
], 1);
734 next
->and = log
== 1;
735 next
->index
= (int)(*tt
)++;
737 /* Append to our chain of expressions. */
755 * Parse a terminal expression with the grammar as defined in
757 * Return NULL if we fail the parse.
760 exprterm(char *buf
, int cs
)
767 memset(&e
, 0, sizeof(struct expr
));
769 /* Choose regex or substring match. */
771 if (NULL
== (e
.v
= strpbrk(buf
, "=~"))) {
775 e
.regex
= '~' == *e
.v
;
779 /* Determine the record types to search for. */
783 while (NULL
!= (key
= strsep(&buf
, ","))) {
785 while (types
[i
].mask
&&
786 strcmp(types
[i
].name
, key
))
788 e
.mask
|= types
[i
].mask
;
792 e
.mask
= TYPE_Nm
| TYPE_Nd
;
795 i
= REG_EXTENDED
| REG_NOSUB
| (cs
? 0 : REG_ICASE
);
796 if (regcomp(&e
.re
, e
.v
, i
))
800 e
.v
= mandoc_strdup(e
.v
);
802 p
= mandoc_calloc(1, sizeof(struct expr
));
803 memcpy(p
, &e
, sizeof(struct expr
));
808 exprfree(struct expr
*p
)
814 exprfree(p
->subexpr
);
825 exprmark(const struct expr
*p
, const char *cp
,
826 uint64_t mask
, int *ms
)
829 for ( ; p
; p
= p
->next
) {
831 if (exprmark(p
->subexpr
, cp
, mask
, ms
))
834 } else if ( ! (mask
& p
->mask
))
838 if (regexec(&p
->re
, cp
, 0, NULL
, 0))
840 } else if (NULL
== strcasestr(cp
, p
->v
))
853 expreval(const struct expr
*p
, int *ms
)
858 * AND has precedence over OR. Analysis is left-right, though
859 * it doesn't matter because there are no side-effects.
860 * Thus, step through pairwise ANDs and accumulate their Boolean
861 * evaluation. If we encounter a single true AND collection or
862 * standalone term, the whole expression is true (by definition
866 for (match
= 0; p
&& ! match
; p
= p
->next
) {
867 /* Evaluate a subexpression, if applicable. */
868 if (p
->subexpr
&& ! ms
[p
->index
])
869 ms
[p
->index
] = expreval(p
->subexpr
, ms
);
871 match
= ms
[p
->index
];
872 for ( ; p
->next
&& p
->next
->and; p
= p
->next
) {
873 /* Evaluate a subexpression, if applicable. */
874 if (p
->next
->subexpr
&& ! ms
[p
->next
->index
])
876 expreval(p
->next
->subexpr
, ms
);
877 match
= match
&& ms
[p
->next
->index
];
885 * First, update the array of terms for which this expression evaluates
887 * Second, logically evaluate all terms over the updated array of truth
889 * If this evaluates to true, mark the expression as satisfied.
892 exprexec(const struct expr
*e
, const char *cp
,
893 uint64_t mask
, struct rec
*r
)
896 assert(0 == r
->matched
);
897 exprmark(e
, cp
, mask
, r
->matches
);
898 r
->matched
= expreval(e
, r
->matches
);