]>
git.cameronkatri.com Git - mandoc.git/blob - apropos_db.c
1 /* $Id: apropos_db.c,v 1.17 2011/12/01 23:46:26 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.
27 #include <arpa/inet.h>
36 #include "apropos_db.h"
40 struct res res
; /* resulting record info */
42 * Maintain a binary tree for checking the uniqueness of `rec'
43 * when adding elements to the results array.
44 * Since the results array is dynamic, use offset in the array
45 * instead of a pointer to the structure.
49 int matched
; /* expression is true */
50 int *matches
; /* partial truth evaluations */
54 int regex
; /* is regex? */
55 int index
; /* index in match array */
56 uint64_t mask
; /* type-mask */
57 int and; /* is rhs of logical AND? */
58 char *v
; /* search value */
59 regex_t re
; /* compiled re, if regex */
60 struct expr
*next
; /* next in sequence */
70 struct rec
*node
; /* record array for dir tree */
71 int len
; /* length of record array */
74 static const struct type types
[] = {
118 static DB
*btree_open(void);
119 static int btree_read(const DBT
*, const DBT
*,
120 const struct mchars
*,
121 struct db_val
*, char **);
122 static int expreval(const struct expr
*, int *);
123 static void exprexec(const struct expr
*,
124 const char *, uint64_t, struct rec
*);
125 static int exprmark(const struct expr
*,
126 const char *, uint64_t, int *);
127 static struct expr
*exprexpr(int, char *[], int *, int *, size_t *);
128 static struct expr
*exprterm(char *, int);
129 static DB
*index_open(void);
130 static int index_read(const DBT
*, const DBT
*, int,
131 const struct mchars
*, struct rec
*);
132 static void norm_string(const char *,
133 const struct mchars
*, char **);
134 static size_t norm_utf8(unsigned int, char[7]);
135 static void recfree(struct rec
*);
136 static int single_search(struct rectree
*, const struct opts
*,
137 const struct expr
*, size_t terms
,
138 struct mchars
*, int);
141 * Open the keyword mandoc-db database.
149 memset(&info
, 0, sizeof(BTREEINFO
));
152 db
= dbopen(MANDOC_DB
, O_RDONLY
, 0, DB_BTREE
, &info
);
160 * Read a keyword from the database and normalise it.
161 * Return 0 if the database is insane, else 1.
164 btree_read(const DBT
*k
, const DBT
*v
,
165 const struct mchars
*mc
,
166 struct db_val
*dbv
, char **buf
)
168 const struct db_val
*vp
;
170 /* Are our sizes sane? */
171 if (k
->size
< 2 || sizeof(struct db_val
) != v
->size
)
174 /* Is our string nil-terminated? */
175 if ('\0' != ((const char *)k
->data
)[(int)k
->size
- 1])
179 norm_string((const char *)k
->data
, mc
, buf
);
180 dbv
->rec
= ntohl(vp
->rec
);
181 dbv
->mask
= vp
->mask
;
186 * Take a Unicode codepoint and produce its UTF-8 encoding.
187 * This isn't the best way to do this, but it works.
188 * The magic numbers are from the UTF-8 packaging.
189 * They're not as scary as they seem: read the UTF-8 spec for details.
192 norm_utf8(unsigned int cp
, char out
[7])
198 if (cp
<= 0x0000007F) {
201 } else if (cp
<= 0x000007FF) {
203 out
[0] = (cp
>> 6 & 31) | 192;
204 out
[1] = (cp
& 63) | 128;
205 } else if (cp
<= 0x0000FFFF) {
207 out
[0] = (cp
>> 12 & 15) | 224;
208 out
[1] = (cp
>> 6 & 63) | 128;
209 out
[2] = (cp
& 63) | 128;
210 } else if (cp
<= 0x001FFFFF) {
212 out
[0] = (cp
>> 18 & 7) | 240;
213 out
[1] = (cp
>> 12 & 63) | 128;
214 out
[2] = (cp
>> 6 & 63) | 128;
215 out
[3] = (cp
& 63) | 128;
216 } else if (cp
<= 0x03FFFFFF) {
218 out
[0] = (cp
>> 24 & 3) | 248;
219 out
[1] = (cp
>> 18 & 63) | 128;
220 out
[2] = (cp
>> 12 & 63) | 128;
221 out
[3] = (cp
>> 6 & 63) | 128;
222 out
[4] = (cp
& 63) | 128;
223 } else if (cp
<= 0x7FFFFFFF) {
225 out
[0] = (cp
>> 30 & 1) | 252;
226 out
[1] = (cp
>> 24 & 63) | 128;
227 out
[2] = (cp
>> 18 & 63) | 128;
228 out
[3] = (cp
>> 12 & 63) | 128;
229 out
[4] = (cp
>> 6 & 63) | 128;
230 out
[5] = (cp
& 63) | 128;
239 * Normalise strings from the index and database.
240 * These strings are escaped as defined by mandoc_char(7) along with
241 * other goop in mandoc.h (e.g., soft hyphens).
242 * This function normalises these into a nice UTF-8 string.
243 * Returns 0 if the database is fucked.
246 norm_string(const char *val
, const struct mchars
*mc
, char **buf
)
250 const char *seq
, *cpp
;
253 static const char res
[] = { '\\', '\t',
254 ASCII_NBRSP
, ASCII_HYPH
, '\0' };
256 /* Pre-allocate by the length of the input */
258 bsz
= strlen(val
) + 1;
259 *buf
= mandoc_realloc(*buf
, bsz
);
262 while ('\0' != *val
) {
264 * Halt on the first escape sequence.
265 * This also halts on the end of string, in which case
266 * we just copy, fallthrough, and exit the loop.
268 if ((sz
= strcspn(val
, res
)) > 0) {
269 memcpy(&(*buf
)[pos
], val
, sz
);
274 if (ASCII_HYPH
== *val
) {
278 } else if ('\t' == *val
|| ASCII_NBRSP
== *val
) {
282 } else if ('\\' != *val
)
285 /* Read past the slash. */
291 * Parse the escape sequence and see if it's a
292 * predefined character or special character.
295 esc
= mandoc_escape(&val
, &seq
, &len
);
296 if (ESCAPE_ERROR
== esc
)
300 * XXX - this just does UTF-8, but we need to know
301 * beforehand whether we should do text substitution.
305 case (ESCAPE_SPECIAL
):
306 if (0 != (u
= mchars_spec2cp(mc
, seq
, len
)))
314 * If we have a Unicode codepoint, try to convert that
315 * to a UTF-8 byte string.
319 if (0 == (sz
= norm_utf8(u
, utfbuf
)))
322 /* Copy the rendered glyph into the stream. */
327 *buf
= mandoc_realloc(*buf
, bsz
);
329 memcpy(&(*buf
)[pos
], cpp
, sz
);
337 * Open the filename-index mandoc-db database.
338 * Returns NULL if opening failed.
345 db
= dbopen(MANDOC_IDX
, O_RDONLY
, 0, DB_RECNO
, NULL
);
353 * Safely unpack from an index file record into the structure.
354 * Returns 1 if an entry was unpacked, 0 if the database is insane.
357 index_read(const DBT
*key
, const DBT
*val
, int index
,
358 const struct mchars
*mc
, struct rec
*rec
)
363 #define INDEX_BREAD(_dst) \
365 if (NULL == (np = memchr(cp, '\0', left))) \
367 norm_string(cp, mc, &(_dst)); \
368 left -= (np - cp) + 1; \
370 } while (/* CONSTCOND */ 0)
373 cp
= (char *)val
->data
;
375 rec
->res
.rec
= *(recno_t
*)key
->data
;
376 rec
->res
.volume
= index
;
378 INDEX_BREAD(rec
->res
.type
);
379 INDEX_BREAD(rec
->res
.file
);
380 INDEX_BREAD(rec
->res
.cat
);
381 INDEX_BREAD(rec
->res
.title
);
382 INDEX_BREAD(rec
->res
.arch
);
383 INDEX_BREAD(rec
->res
.desc
);
388 * Search mandocdb databases in paths for expression "expr".
389 * Filter out by "opts".
390 * Call "res" with the results, which may be zero.
391 * Return 0 if there was a database error, else return 1.
394 apropos_search(int pathsz
, char **paths
, const struct opts
*opts
,
395 const struct expr
*expr
, size_t terms
, void *arg
,
396 void (*res
)(struct res
*, size_t, void *))
403 memset(&tree
, 0, sizeof(struct rectree
));
409 * Main loop. Change into the directory containing manpage
410 * databases. Run our expession over each database in the set.
413 for (i
= 0; i
< pathsz
; i
++) {
416 if ( ! single_search(&tree
, opts
, expr
, terms
, mc
, i
))
421 * Count matching files, transfer to a "clean" array, then feed
422 * them to the output handler.
425 for (mlen
= i
= 0; i
< tree
.len
; i
++)
426 if (tree
.node
[i
].matched
)
429 ress
= mandoc_malloc(mlen
* sizeof(struct res
));
431 for (mlen
= i
= 0; i
< tree
.len
; i
++)
432 if (tree
.node
[i
].matched
)
433 memcpy(&ress
[mlen
++], &tree
.node
[i
].res
,
436 (*res
)(ress
, mlen
, arg
);
441 for (i
= 0; i
< tree
.len
; i
++)
442 recfree(&tree
.node
[i
]);
450 single_search(struct rectree
*tree
, const struct opts
*opts
,
451 const struct expr
*expr
, size_t terms
,
452 struct mchars
*mc
, int vol
)
469 memset(&r
, 0, sizeof(struct rec
));
471 if (NULL
== (btree
= btree_open()))
474 if (NULL
== (idx
= index_open())) {
475 (*btree
->close
)(btree
);
479 while (0 == (ch
= (*btree
->seq
)(btree
, &key
, &val
, R_NEXT
))) {
480 if ( ! btree_read(&key
, &val
, mc
, &vb
, &buf
))
484 * See if this keyword record matches any of the
485 * expressions we have stored.
487 if ( ! exprmark(expr
, buf
, vb
.mask
, NULL
))
491 * O(log n) scan for prior records. Since a record
492 * number is unbounded, this has decent performance over
493 * a complex hash function.
496 for (leaf
= root
; leaf
>= 0; )
497 if (vb
.rec
> rs
[leaf
].res
.rec
&&
500 else if (vb
.rec
< rs
[leaf
].res
.rec
&&
507 * If we find a record, see if it has already evaluated
508 * to true. If it has, great, just keep going. If not,
509 * try to evaluate it now and continue anyway.
512 if (leaf
>= 0 && rs
[leaf
].res
.rec
== vb
.rec
) {
513 if (0 == rs
[leaf
].matched
)
514 exprexec(expr
, buf
, vb
.mask
, &rs
[leaf
]);
519 * We have a new file to examine.
520 * Extract the manpage's metadata from the index
521 * database, then begin partial evaluation.
525 key
.size
= sizeof(recno_t
);
527 if (0 != (*idx
->get
)(idx
, &key
, &val
, 0))
531 if ( ! index_read(&key
, &val
, vol
, mc
, &r
))
534 /* XXX: this should be elsewhere, I guess? */
536 if (opts
->cat
&& strcasecmp(opts
->cat
, r
.res
.cat
))
538 if (opts
->arch
&& strcasecmp(opts
->arch
, r
.res
.arch
))
541 tree
->node
= rs
= mandoc_realloc
542 (rs
, (tree
->len
+ 1) * sizeof(struct rec
));
544 memcpy(&rs
[tree
->len
], &r
, sizeof(struct rec
));
545 rs
[tree
->len
].matches
=
546 mandoc_calloc(terms
, sizeof(int));
548 exprexec(expr
, buf
, vb
.mask
, &rs
[tree
->len
]);
550 /* Append to our tree. */
553 if (vb
.rec
> rs
[leaf
].res
.rec
)
554 rs
[leaf
].rhs
= tree
->len
;
556 rs
[leaf
].lhs
= tree
->len
;
560 memset(&r
, 0, sizeof(struct rec
));
564 (*btree
->close
)(btree
);
572 recfree(struct rec
*rec
)
578 free(rec
->res
.title
);
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 rec
*r
)
876 assert(0 == r
->matched
);
877 exprmark(e
, cp
, mask
, r
->matches
);
878 r
->matched
= expreval(e
, r
->matches
);