]>
git.cameronkatri.com Git - mandoc.git/blob - apropos_db.c
1 /* $Id: apropos_db.c,v 1.21 2011/12/03 18:47:09 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
[] = {
124 static DB
*btree_open(void);
125 static int btree_read(const DBT
*, const DBT
*,
126 const struct mchars
*,
127 struct db_val
*, 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
,
171 const struct mchars
*mc
,
172 struct db_val
*dbv
, char **buf
)
174 const struct db_val
*vp
;
176 /* Are our sizes sane? */
177 if (k
->size
< 2 || sizeof(struct db_val
) != v
->size
)
180 /* Is our string nil-terminated? */
181 if ('\0' != ((const char *)k
->data
)[(int)k
->size
- 1])
185 norm_string((const char *)k
->data
, mc
, buf
);
186 dbv
->rec
= betoh32(vp
->rec
);
187 dbv
->mask
= betoh64(vp
->mask
);
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
)
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)
379 cp
= (char *)val
->data
;
381 rec
->res
.rec
= *(recno_t
*)key
->data
;
382 rec
->res
.volume
= index
;
384 INDEX_BREAD(rec
->res
.type
);
385 INDEX_BREAD(rec
->res
.file
);
386 INDEX_BREAD(rec
->res
.cat
);
387 INDEX_BREAD(rec
->res
.title
);
388 INDEX_BREAD(rec
->res
.arch
);
389 INDEX_BREAD(rec
->res
.desc
);
394 * Search mandocdb databases in paths for expression "expr".
395 * Filter out by "opts".
396 * Call "res" with the results, which may be zero.
397 * Return 0 if there was a database error, else return 1.
400 apropos_search(int pathsz
, char **paths
, const struct opts
*opts
,
401 const struct expr
*expr
, size_t terms
, void *arg
,
402 void (*res
)(struct res
*, size_t, void *))
409 memset(&tree
, 0, sizeof(struct rectree
));
415 * Main loop. Change into the directory containing manpage
416 * databases. Run our expession over each database in the set.
419 for (i
= 0; i
< pathsz
; i
++) {
422 if ( ! single_search(&tree
, opts
, expr
, terms
, mc
, i
))
427 * Count matching files, transfer to a "clean" array, then feed
428 * them to the output handler.
431 for (mlen
= i
= 0; i
< tree
.len
; i
++)
432 if (tree
.node
[i
].matched
)
435 ress
= mandoc_malloc(mlen
* sizeof(struct res
));
437 for (mlen
= i
= 0; i
< tree
.len
; i
++)
438 if (tree
.node
[i
].matched
)
439 memcpy(&ress
[mlen
++], &tree
.node
[i
].res
,
442 (*res
)(ress
, mlen
, arg
);
447 for (i
= 0; i
< tree
.len
; i
++)
448 recfree(&tree
.node
[i
]);
456 single_search(struct rectree
*tree
, const struct opts
*opts
,
457 const struct expr
*expr
, size_t terms
,
458 struct mchars
*mc
, int vol
)
475 memset(&r
, 0, sizeof(struct rec
));
477 if (NULL
== (btree
= btree_open()))
480 if (NULL
== (idx
= index_open())) {
481 (*btree
->close
)(btree
);
485 while (0 == (ch
= (*btree
->seq
)(btree
, &key
, &val
, R_NEXT
))) {
486 if ( ! btree_read(&key
, &val
, mc
, &vb
, &buf
))
490 * See if this keyword record matches any of the
491 * expressions we have stored.
493 if ( ! exprmark(expr
, buf
, vb
.mask
, NULL
))
497 * O(log n) scan for prior records. Since a record
498 * number is unbounded, this has decent performance over
499 * a complex hash function.
502 for (leaf
= root
; leaf
>= 0; )
503 if (vb
.rec
> rs
[leaf
].res
.rec
&&
506 else if (vb
.rec
< rs
[leaf
].res
.rec
&&
513 * If we find a record, see if it has already evaluated
514 * to true. If it has, great, just keep going. If not,
515 * try to evaluate it now and continue anyway.
518 if (leaf
>= 0 && rs
[leaf
].res
.rec
== vb
.rec
) {
519 if (0 == rs
[leaf
].matched
)
520 exprexec(expr
, buf
, vb
.mask
, &rs
[leaf
]);
525 * We have a new file to examine.
526 * Extract the manpage's metadata from the index
527 * database, then begin partial evaluation.
531 key
.size
= sizeof(recno_t
);
533 if (0 != (*idx
->get
)(idx
, &key
, &val
, 0))
537 if ( ! index_read(&key
, &val
, vol
, mc
, &r
))
540 /* XXX: this should be elsewhere, I guess? */
542 if (opts
->cat
&& strcasecmp(opts
->cat
, r
.res
.cat
))
544 if (opts
->arch
&& strcasecmp(opts
->arch
, r
.res
.arch
))
547 tree
->node
= rs
= mandoc_realloc
548 (rs
, (tree
->len
+ 1) * sizeof(struct rec
));
550 memcpy(&rs
[tree
->len
], &r
, sizeof(struct rec
));
551 rs
[tree
->len
].matches
=
552 mandoc_calloc(terms
, sizeof(int));
554 exprexec(expr
, buf
, vb
.mask
, &rs
[tree
->len
]);
556 /* Append to our tree. */
559 if (vb
.rec
> rs
[leaf
].res
.rec
)
560 rs
[leaf
].rhs
= tree
->len
;
562 rs
[leaf
].lhs
= tree
->len
;
566 memset(&r
, 0, sizeof(struct rec
));
570 (*btree
->close
)(btree
);
578 recfree(struct rec
*rec
)
584 free(rec
->res
.title
);
592 * Compile a list of straight-up terms.
593 * The arguments are re-written into ~[[:<:]]term[[:>:]], or "term"
594 * surrounded by word boundaries, then pumped through exprterm().
595 * Terms are case-insensitive.
596 * This emulates whatis(1) behaviour.
599 termcomp(int argc
, char *argv
[], size_t *tt
)
603 struct expr
*e
, *next
;
610 for (pos
= argc
- 1; pos
>= 0; pos
--) {
611 sz
= strlen(argv
[pos
]) + 18;
612 buf
= mandoc_realloc(buf
, sz
);
613 strlcpy(buf
, "Nm~[[:<:]]", sz
);
614 strlcat(buf
, argv
[pos
], sz
);
615 strlcat(buf
, "[[:>:]]", sz
);
616 if (NULL
== (next
= exprterm(buf
, 0))) {
631 * Compile a sequence of logical expressions.
632 * See apropos.1 for a grammar of this sequence.
635 exprcomp(int argc
, char *argv
[], size_t *tt
)
643 e
= exprexpr(argc
, argv
, &pos
, &lvl
, tt
);
645 if (0 == lvl
&& pos
>= argc
)
653 * Compile an array of tokens into an expression.
654 * An informal expression grammar is defined in apropos(1).
655 * Return NULL if we fail doing so. All memory will be cleaned up.
656 * Return the root of the expression sequence if alright.
659 exprexpr(int argc
, char *argv
[], int *pos
, int *lvl
, size_t *tt
)
661 struct expr
*e
, *first
, *next
;
666 for ( ; *pos
< argc
; (*pos
)++) {
670 * Close out a subexpression.
673 if (NULL
!= e
&& 0 == strcmp(")", argv
[*pos
])) {
680 * Small note: if we're just starting, don't let "-a"
681 * and "-o" be considered logical operators: they're
682 * just tokens unless pairwise joining, in which case we
683 * record their existence (or assume "OR").
687 if (NULL
!= e
&& 0 == strcmp("-a", argv
[*pos
]))
689 else if (NULL
!= e
&& 0 == strcmp("-o", argv
[*pos
]))
692 if (log
> 0 && ++(*pos
) >= argc
)
696 * Now we parse the term part. This can begin with
697 * "-i", in which case the expression is case
701 if (0 == strcmp("(", argv
[*pos
])) {
704 next
= mandoc_calloc(1, sizeof(struct expr
));
705 next
->subexpr
= exprexpr(argc
, argv
, pos
, lvl
, tt
);
706 if (NULL
== next
->subexpr
) {
710 } else if (0 == strcmp("-i", argv
[*pos
])) {
711 if (++(*pos
) >= argc
)
713 next
= exprterm(argv
[*pos
], 0);
715 next
= exprterm(argv
[*pos
], 1);
720 next
->and = log
== 1;
721 next
->index
= (int)(*tt
)++;
723 /* Append to our chain of expressions. */
741 * Parse a terminal expression with the grammar as defined in
743 * Return NULL if we fail the parse.
746 exprterm(char *buf
, int cs
)
753 memset(&e
, 0, sizeof(struct expr
));
755 /* Choose regex or substring match. */
757 if (NULL
== (e
.v
= strpbrk(buf
, "=~"))) {
761 e
.regex
= '~' == *e
.v
;
765 /* Determine the record types to search for. */
769 while (NULL
!= (key
= strsep(&buf
, ","))) {
771 while (types
[i
].mask
&&
772 strcmp(types
[i
].name
, key
))
774 e
.mask
|= types
[i
].mask
;
778 e
.mask
= TYPE_Nm
| TYPE_Nd
;
781 i
= REG_EXTENDED
| REG_NOSUB
| (cs
? 0 : REG_ICASE
);
782 if (regcomp(&e
.re
, e
.v
, i
))
786 e
.v
= mandoc_strdup(e
.v
);
788 p
= mandoc_calloc(1, sizeof(struct expr
));
789 memcpy(p
, &e
, sizeof(struct expr
));
794 exprfree(struct expr
*p
)
800 exprfree(p
->subexpr
);
811 exprmark(const struct expr
*p
, const char *cp
,
812 uint64_t mask
, int *ms
)
815 for ( ; p
; p
= p
->next
) {
817 if (exprmark(p
->subexpr
, cp
, mask
, ms
))
820 } else if ( ! (mask
& p
->mask
))
824 if (regexec(&p
->re
, cp
, 0, NULL
, 0))
826 } else if (NULL
== strcasestr(cp
, p
->v
))
839 expreval(const struct expr
*p
, int *ms
)
844 * AND has precedence over OR. Analysis is left-right, though
845 * it doesn't matter because there are no side-effects.
846 * Thus, step through pairwise ANDs and accumulate their Boolean
847 * evaluation. If we encounter a single true AND collection or
848 * standalone term, the whole expression is true (by definition
852 for (match
= 0; p
&& ! match
; p
= p
->next
) {
853 /* Evaluate a subexpression, if applicable. */
854 if (p
->subexpr
&& ! ms
[p
->index
])
855 ms
[p
->index
] = expreval(p
->subexpr
, ms
);
857 match
= ms
[p
->index
];
858 for ( ; p
->next
&& p
->next
->and; p
= p
->next
) {
859 /* Evaluate a subexpression, if applicable. */
860 if (p
->next
->subexpr
&& ! ms
[p
->next
->index
])
862 expreval(p
->next
->subexpr
, ms
);
863 match
= match
&& ms
[p
->next
->index
];
871 * First, update the array of terms for which this expression evaluates
873 * Second, logically evaluate all terms over the updated array of truth
875 * If this evaluates to true, mark the expression as satisfied.
878 exprexec(const struct expr
*e
, const char *cp
,
879 uint64_t mask
, struct rec
*r
)
882 assert(0 == r
->matched
);
883 exprmark(e
, cp
, mask
, r
->matches
);
884 r
->matched
= expreval(e
, r
->matches
);