]>
git.cameronkatri.com Git - mandoc.git/blob - apropos_db.c
1 /* $Id: apropos_db.c,v 1.29 2012/03/23 05:07:35 kristaps 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
));
159 db
= dbopen(MANDOC_DB
, O_RDONLY
, 0, DB_BTREE
, &info
);
167 * Read a keyword from the database and normalise it.
168 * Return 0 if the database is insane, else 1.
171 btree_read(const DBT
*k
, const DBT
*v
, const struct mchars
*mc
,
172 uint64_t *mask
, recno_t
*rec
, char **buf
)
176 /* Are our sizes sane? */
177 if (k
->size
< 2 || sizeof(vbuf
) != v
->size
)
180 /* Is our string nil-terminated? */
181 if ('\0' != ((const char *)k
->data
)[(int)k
->size
- 1])
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]);
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.
198 norm_utf8(unsigned int cp
, char out
[7])
204 if (cp
<= 0x0000007F) {
207 } else if (cp
<= 0x000007FF) {
209 out
[0] = (cp
>> 6 & 31) | 192;
210 out
[1] = (cp
& 63) | 128;
211 } else if (cp
<= 0x0000FFFF) {
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) {
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) {
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) {
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;
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.
252 norm_string(const char *val
, const struct mchars
*mc
, char **buf
)
256 const char *seq
, *cpp
;
259 static const char res
[] = { '\\', '\t',
260 ASCII_NBRSP
, ASCII_HYPH
, '\0' };
262 /* Pre-allocate by the length of the input */
264 bsz
= strlen(val
) + 1;
265 *buf
= mandoc_realloc(*buf
, bsz
);
268 while ('\0' != *val
) {
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.
274 if ((sz
= strcspn(val
, res
)) > 0) {
275 memcpy(&(*buf
)[pos
], val
, sz
);
280 if (ASCII_HYPH
== *val
) {
284 } else if ('\t' == *val
|| ASCII_NBRSP
== *val
) {
288 } else if ('\\' != *val
)
291 /* Read past the slash. */
297 * Parse the escape sequence and see if it's a
298 * predefined character or special character.
301 esc
= mandoc_escape(&val
, &seq
, &len
);
302 if (ESCAPE_ERROR
== esc
)
306 * XXX - this just does UTF-8, but we need to know
307 * beforehand whether we should do text substitution.
311 case (ESCAPE_SPECIAL
):
312 if (0 != (u
= mchars_spec2cp(mc
, seq
, len
)))
320 * If we have a Unicode codepoint, try to convert that
321 * to a UTF-8 byte string.
325 if (0 == (sz
= norm_utf8(u
, utfbuf
)))
328 /* Copy the rendered glyph into the stream. */
333 *buf
= mandoc_realloc(*buf
, bsz
);
335 memcpy(&(*buf
)[pos
], cpp
, sz
);
343 * Open the filename-index mandoc-db database.
344 * Returns NULL if opening failed.
351 db
= dbopen(MANDOC_IDX
, O_RDONLY
, 0, DB_RECNO
, NULL
);
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.
363 index_read(const DBT
*key
, const DBT
*val
, int index
,
364 const struct mchars
*mc
, struct rec
*rec
)
370 #define INDEX_BREAD(_dst) \
372 if (NULL == (np = memchr(cp, '\0', left))) \
374 norm_string(cp, mc, &(_dst)); \
375 left -= (np - cp) + 1; \
377 } while (/* CONSTCOND */ 0)
379 if (0 == (left
= val
->size
))
383 assert(sizeof(recno_t
) == key
->size
);
384 memcpy(&rec
->res
.rec
, key
->data
, key
->size
);
385 rec
->res
.volume
= index
;
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
;
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
);
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.
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 *))
421 memset(&tree
, 0, sizeof(struct rectree
));
427 * Main loop. Change into the directory containing manpage
428 * databases. Run our expession over each database in the set.
431 for (i
= 0; i
< pathsz
; i
++) {
434 if ( ! single_search(&tree
, opts
, expr
, terms
, mc
, i
))
439 * Count matching files, transfer to a "clean" array, then feed
440 * them to the output handler.
443 for (mlen
= i
= 0; i
< tree
.len
; i
++)
444 if (tree
.node
[i
].matched
)
447 ress
= mandoc_malloc(mlen
* sizeof(struct res
));
449 for (mlen
= i
= 0; i
< tree
.len
; i
++)
450 if (tree
.node
[i
].matched
)
451 memcpy(&ress
[mlen
++], &tree
.node
[i
].res
,
454 (*res
)(ress
, mlen
, arg
);
459 for (i
= 0; i
< tree
.len
; i
++)
460 recfree(&tree
.node
[i
]);
468 single_search(struct rectree
*tree
, const struct opts
*opts
,
469 const struct expr
*expr
, size_t terms
,
470 struct mchars
*mc
, int vol
)
488 memset(&r
, 0, sizeof(struct rec
));
490 if (NULL
== (btree
= btree_open()))
493 if (NULL
== (idx
= index_open())) {
494 (*btree
->close
)(btree
);
498 while (0 == (ch
= (*btree
->seq
)(btree
, &key
, &val
, R_NEXT
))) {
499 if ( ! btree_read(&key
, &val
, mc
, &mask
, &rec
, &buf
))
503 * See if this keyword record matches any of the
504 * expressions we have stored.
506 if ( ! exprmark(expr
, buf
, mask
, NULL
))
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.
515 for (leaf
= root
; leaf
>= 0; )
516 if (rec
> rs
[leaf
].res
.rec
&&
519 else if (rec
< rs
[leaf
].res
.rec
&&
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.
531 if (leaf
>= 0 && rs
[leaf
].res
.rec
== rec
) {
532 if (0 == rs
[leaf
].matched
)
533 exprexec(expr
, buf
, mask
, &rs
[leaf
]);
538 * We have a new file to examine.
539 * Extract the manpage's metadata from the index
540 * database, then begin partial evaluation.
544 key
.size
= sizeof(recno_t
);
546 if (0 != (*idx
->get
)(idx
, &key
, &val
, 0))
550 if ( ! index_read(&key
, &val
, vol
, mc
, &r
))
553 /* XXX: this should be elsewhere, I guess? */
555 if (opts
->cat
&& strcasecmp(opts
->cat
, r
.res
.cat
))
558 if (opts
->arch
&& *r
.res
.arch
)
559 if (strcasecmp(opts
->arch
, r
.res
.arch
))
562 tree
->node
= rs
= mandoc_realloc
563 (rs
, (tree
->len
+ 1) * sizeof(struct rec
));
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));
570 exprexec(expr
, buf
, mask
, &rs
[tree
->len
]);
572 /* Append to our tree. */
575 if (rec
> rs
[leaf
].res
.rec
)
576 rs
[leaf
].rhs
= tree
->len
;
578 rs
[leaf
].lhs
= tree
->len
;
585 (*btree
->close
)(btree
);
594 recfree(struct rec
*rec
)
599 free(rec
->res
.title
);
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.
614 termcomp(int argc
, char *argv
[], size_t *tt
)
618 struct expr
*e
, *next
;
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))) {
646 * Compile a sequence of logical expressions.
647 * See apropos.1 for a grammar of this sequence.
650 exprcomp(int argc
, char *argv
[], size_t *tt
)
658 e
= exprexpr(argc
, argv
, &pos
, &lvl
, tt
);
660 if (0 == lvl
&& pos
>= argc
)
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.
674 exprexpr(int argc
, char *argv
[], int *pos
, int *lvl
, size_t *tt
)
676 struct expr
*e
, *first
, *next
;
681 for ( ; *pos
< argc
; (*pos
)++) {
685 * Close out a subexpression.
688 if (NULL
!= e
&& 0 == strcmp(")", argv
[*pos
])) {
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").
702 if (NULL
!= e
&& 0 == strcmp("-a", argv
[*pos
]))
704 else if (NULL
!= e
&& 0 == strcmp("-o", argv
[*pos
]))
707 if (log
> 0 && ++(*pos
) >= argc
)
711 * Now we parse the term part. This can begin with
712 * "-i", in which case the expression is case
716 if (0 == strcmp("(", argv
[*pos
])) {
719 next
= mandoc_calloc(1, sizeof(struct expr
));
720 next
->subexpr
= exprexpr(argc
, argv
, pos
, lvl
, tt
);
721 if (NULL
== next
->subexpr
) {
725 } else if (0 == strcmp("-i", argv
[*pos
])) {
726 if (++(*pos
) >= argc
)
728 next
= exprterm(argv
[*pos
], 0);
730 next
= exprterm(argv
[*pos
], 1);
735 next
->and = log
== 1;
736 next
->index
= (int)(*tt
)++;
738 /* Append to our chain of expressions. */
756 * Parse a terminal expression with the grammar as defined in
758 * Return NULL if we fail the parse.
761 exprterm(char *buf
, int cs
)
768 memset(&e
, 0, sizeof(struct expr
));
770 /* Choose regex or substring match. */
772 if (NULL
== (e
.v
= strpbrk(buf
, "=~"))) {
776 e
.regex
= '~' == *e
.v
;
780 /* Determine the record types to search for. */
784 while (NULL
!= (key
= strsep(&buf
, ","))) {
786 while (types
[i
].mask
&&
787 strcmp(types
[i
].name
, key
))
789 e
.mask
|= types
[i
].mask
;
793 e
.mask
= TYPE_Nm
| TYPE_Nd
;
796 i
= REG_EXTENDED
| REG_NOSUB
| (cs
? 0 : REG_ICASE
);
797 if (regcomp(&e
.re
, e
.v
, i
))
801 e
.v
= mandoc_strdup(e
.v
);
803 p
= mandoc_calloc(1, sizeof(struct expr
));
804 memcpy(p
, &e
, sizeof(struct expr
));
809 exprfree(struct expr
*p
)
815 exprfree(p
->subexpr
);
826 exprmark(const struct expr
*p
, const char *cp
,
827 uint64_t mask
, int *ms
)
830 for ( ; p
; p
= p
->next
) {
832 if (exprmark(p
->subexpr
, cp
, mask
, ms
))
835 } else if ( ! (mask
& p
->mask
))
839 if (regexec(&p
->re
, cp
, 0, NULL
, 0))
841 } else if (NULL
== strcasestr(cp
, p
->v
))
854 expreval(const struct expr
*p
, int *ms
)
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
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
);
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
])
877 expreval(p
->next
->subexpr
, ms
);
878 match
= match
&& ms
[p
->next
->index
];
886 * First, update the array of terms for which this expression evaluates
888 * Second, logically evaluate all terms over the updated array of truth
890 * If this evaluates to true, mark the expression as satisfied.
893 exprexec(const struct expr
*e
, const char *cp
,
894 uint64_t mask
, struct rec
*r
)
897 assert(0 == r
->matched
);
898 exprmark(e
, cp
, mask
, r
->matches
);
899 r
->matched
= expreval(e
, r
->matches
);