1 /* kwset.c - search for any of a set of keywords.
2 Copyright (C) 1989, 1998, 2000, 2005, 2007, 2009-2011 Free Software
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 3, or (at your option)
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
20 /* Written August 1989 by Mike Haertel.
21 The author may be reached (Email) at the address mike@ai.mit.edu,
22 or (US mail) as Mike Haertel c/o Free Software Foundation. */
24 /* The algorithm implemented by these routines bears a startling resemblence
25 to one discovered by Beate Commentz-Walter, although it is not identical.
26 See "A String Matching Algorithm Fast on the Average," Technical Report,
27 IBM-Germany, Scientific Center Heidelberg, Tiergartenstrasse 15, D-6900
28 Heidelberg, Germany. See also Aho, A.V., and M. Corasick, "Efficient
29 String Matching: An Aid to Bibliographic Search," CACM June 1975,
30 Vol. 18, No. 6, which describes the failure function used below. */
33 #include <sys/types.h>
38 #define link kwset_link
43 # define malloc xmalloc
46 #define NCHAR (UCHAR_MAX + 1)
47 #define obstack_chunk_alloc malloc
48 #define obstack_chunk_free free
50 #define U(c) ((unsigned char) (c))
52 /* Balanced tree of edges and labels leaving a given trie node. */
55 struct tree *llink; /* Left link; MUST be first field. */
56 struct tree *rlink; /* Right link (to larger labels). */
57 struct trie *trie; /* Trie node pointed to by this edge. */
58 unsigned char label; /* Label on this edge. */
59 char balance; /* Difference in depths of subtrees. */
62 /* Node of a trie representing a set of reversed keywords. */
65 unsigned int accepting; /* Word index of accepted word, or zero. */
66 struct tree *links; /* Tree of edges leaving this node. */
67 struct trie *parent; /* Parent of this node. */
68 struct trie *next; /* List of all trie nodes in level order. */
69 struct trie *fail; /* Aho-Corasick failure function. */
70 int depth; /* Depth of this node from the root. */
71 int shift; /* Shift function for search failures. */
72 int maxshift; /* Max shift of self and descendents. */
75 /* Structure returned opaquely to the caller, containing everything. */
78 struct obstack obstack; /* Obstack for node allocation. */
79 int words; /* Number of words in the trie. */
80 struct trie *trie; /* The trie itself. */
81 int mind; /* Minimum depth of an accepting node. */
82 int maxd; /* Maximum depth of any node. */
83 unsigned char delta[NCHAR]; /* Delta table for rapid search. */
84 struct trie *next[NCHAR]; /* Table of children of the root. */
85 char *target; /* Target string if there's only one. */
86 int mind2; /* Used in Boyer-Moore search for one string. */
87 char const *trans; /* Character translation table. */
90 /* Allocate and initialize a keyword set object, returning an opaque
91 pointer to it. Return NULL if memory is not available. */
93 kwsalloc (char const *trans)
97 kwset = (struct kwset *) malloc(sizeof (struct kwset));
101 obstack_init(&kwset->obstack);
104 = (struct trie *) obstack_alloc(&kwset->obstack, sizeof (struct trie));
107 kwsfree((kwset_t) kwset);
110 kwset->trie->accepting = 0;
111 kwset->trie->links = NULL;
112 kwset->trie->parent = NULL;
113 kwset->trie->next = NULL;
114 kwset->trie->fail = NULL;
115 kwset->trie->depth = 0;
116 kwset->trie->shift = 0;
117 kwset->mind = INT_MAX;
119 kwset->target = NULL;
120 kwset->trans = trans;
122 return (kwset_t) kwset;
125 /* This upper bound is valid for CHAR_BIT >= 4 and
126 exact for CHAR_BIT in { 4..11, 13, 15, 17, 19 }. */
127 #define DEPTH_SIZE (CHAR_BIT + CHAR_BIT/2)
129 /* Add the given string to the contents of the keyword set. Return NULL
130 for success, an error message otherwise. */
132 kwsincr (kwset_t kws, char const *text, size_t len)
139 struct tree *links[DEPTH_SIZE];
140 enum { L, R } dirs[DEPTH_SIZE];
141 struct tree *t, *r, *l, *rl, *lr;
143 kwset = (struct kwset *) kws;
147 /* Descend the trie (built of reversed keywords) character-by-character,
148 installing new nodes when necessary. */
151 label = kwset->trans ? kwset->trans[U(*--text)] : *--text;
153 /* Descend the tree of outgoing links for this trie node,
154 looking for the current character and keeping track
155 of the path followed. */
157 links[0] = (struct tree *) &trie->links;
161 while (link && label != link->label)
164 if (label < link->label)
165 dirs[depth++] = L, link = link->llink;
167 dirs[depth++] = R, link = link->rlink;
170 /* The current character doesn't have an outgoing link at
171 this trie node, so build a new trie node and install
172 a link in the current trie node's tree. */
175 link = (struct tree *) obstack_alloc(&kwset->obstack,
176 sizeof (struct tree));
178 return _("memory exhausted");
181 link->trie = (struct trie *) obstack_alloc(&kwset->obstack,
182 sizeof (struct trie));
185 obstack_free(&kwset->obstack, link);
186 return _("memory exhausted");
188 link->trie->accepting = 0;
189 link->trie->links = NULL;
190 link->trie->parent = trie;
191 link->trie->next = NULL;
192 link->trie->fail = NULL;
193 link->trie->depth = trie->depth + 1;
194 link->trie->shift = 0;
198 /* Install the new tree node in its parent. */
199 if (dirs[--depth] == L)
200 links[depth]->llink = link;
202 links[depth]->rlink = link;
204 /* Back up the tree fixing the balance flags. */
205 while (depth && !links[depth]->balance)
207 if (dirs[depth] == L)
208 --links[depth]->balance;
210 ++links[depth]->balance;
214 /* Rebalance the tree by pointer rotations if necessary. */
215 if (depth && ((dirs[depth] == L && --links[depth]->balance)
216 || (dirs[depth] == R && ++links[depth]->balance)))
218 switch (links[depth]->balance)
221 switch (dirs[depth + 1])
224 r = links[depth], t = r->llink, rl = t->rlink;
225 t->rlink = r, r->llink = rl;
226 t->balance = r->balance = 0;
229 r = links[depth], l = r->llink, t = l->rlink;
230 rl = t->rlink, lr = t->llink;
231 t->llink = l, l->rlink = lr, t->rlink = r, r->llink = rl;
232 l->balance = t->balance != 1 ? 0 : -1;
233 r->balance = t->balance != (char) -1 ? 0 : 1;
241 switch (dirs[depth + 1])
244 l = links[depth], t = l->rlink, lr = t->llink;
245 t->llink = l, l->rlink = lr;
246 t->balance = l->balance = 0;
249 l = links[depth], r = l->rlink, t = r->llink;
250 lr = t->llink, rl = t->rlink;
251 t->llink = l, l->rlink = lr, t->rlink = r, r->llink = rl;
252 l->balance = t->balance != 1 ? 0 : -1;
253 r->balance = t->balance != (char) -1 ? 0 : 1;
264 if (dirs[depth - 1] == L)
265 links[depth - 1]->llink = t;
267 links[depth - 1]->rlink = t;
274 /* Mark the node we finally reached as accepting, encoding the
275 index number of this word in the keyword set so far. */
276 if (!trie->accepting)
277 trie->accepting = 1 + 2 * kwset->words;
280 /* Keep track of the longest and shortest string of the keyword set. */
281 if (trie->depth < kwset->mind)
282 kwset->mind = trie->depth;
283 if (trie->depth > kwset->maxd)
284 kwset->maxd = trie->depth;
289 /* Enqueue the trie nodes referenced from the given tree in the
292 enqueue (struct tree *tree, struct trie **last)
296 enqueue(tree->llink, last);
297 enqueue(tree->rlink, last);
298 (*last) = (*last)->next = tree->trie;
301 /* Compute the Aho-Corasick failure function for the trie nodes referenced
302 from the given tree, given the failure function for their parent as
303 well as a last resort failure node. */
305 treefails (struct tree const *tree, struct trie const *fail,
306 struct trie *recourse)
313 treefails(tree->llink, fail, recourse);
314 treefails(tree->rlink, fail, recourse);
316 /* Find, in the chain of fails going back to the root, the first
317 node that has a descendent on the current label. */
321 while (link && tree->label != link->label)
322 if (tree->label < link->label)
328 tree->trie->fail = link->trie;
334 tree->trie->fail = recourse;
337 /* Set delta entries for the links of the given tree such that
338 the preexisting delta value is larger than the current depth. */
340 treedelta (struct tree const *tree,
342 unsigned char delta[])
346 treedelta(tree->llink, depth, delta);
347 treedelta(tree->rlink, depth, delta);
348 if (depth < delta[tree->label])
349 delta[tree->label] = depth;
352 /* Return true if A has every label in B. */
354 hasevery (struct tree const *a, struct tree const *b)
358 if (!hasevery(a, b->llink))
360 if (!hasevery(a, b->rlink))
362 while (a && b->label != a->label)
363 if (b->label < a->label)
370 /* Compute a vector, indexed by character code, of the trie nodes
371 referenced from the given tree. */
373 treenext (struct tree const *tree, struct trie *next[])
377 treenext(tree->llink, next);
378 treenext(tree->rlink, next);
379 next[tree->label] = tree->trie;
382 /* Compute the shift for each trie node, as well as the delta
383 table and next cache for the given keyword set. */
385 kwsprep (kwset_t kws)
391 unsigned char delta[NCHAR];
393 kwset = (struct kwset *) kws;
395 /* Initial values for the delta table; will be changed later. The
396 delta entry for a given character is the smallest depth of any
397 node at which an outgoing edge is labeled by that character. */
398 memset(delta, kwset->mind < UCHAR_MAX ? kwset->mind : UCHAR_MAX, NCHAR);
400 /* Check if we can use the simple boyer-moore algorithm, instead
401 of the hairy commentz-walter algorithm. */
402 if (kwset->words == 1 && kwset->trans == NULL)
406 /* Looking for just one string. Extract it from the trie. */
407 kwset->target = obstack_alloc(&kwset->obstack, kwset->mind);
409 return _("memory exhausted");
410 for (i = kwset->mind - 1, curr = kwset->trie; i >= 0; --i)
412 kwset->target[i] = curr->links->label;
413 curr = curr->links->trie;
415 /* Build the Boyer Moore delta. Boy that's easy compared to CW. */
416 for (i = 0; i < kwset->mind; ++i)
417 delta[U(kwset->target[i])] = kwset->mind - (i + 1);
418 /* Find the minimal delta2 shift that we might make after
419 a backwards match has failed. */
420 c = kwset->target[kwset->mind - 1];
421 for (i = kwset->mind - 2; i >= 0; --i)
422 if (kwset->target[i] == c)
424 kwset->mind2 = kwset->mind - (i + 1);
429 struct trie *last, *next[NCHAR];
431 /* Traverse the nodes of the trie in level order, simultaneously
432 computing the delta table, failure function, and shift function. */
433 for (curr = last = kwset->trie; curr; curr = curr->next)
435 /* Enqueue the immediate descendents in the level order queue. */
436 enqueue(curr->links, &last);
438 curr->shift = kwset->mind;
439 curr->maxshift = kwset->mind;
441 /* Update the delta table for the descendents of this node. */
442 treedelta(curr->links, curr->depth, delta);
444 /* Compute the failure function for the decendents of this node. */
445 treefails(curr->links, curr->fail, kwset->trie);
447 /* Update the shifts at each node in the current node's chain
448 of fails back to the root. */
449 for (fail = curr->fail; fail; fail = fail->fail)
451 /* If the current node has some outgoing edge that the fail
452 doesn't, then the shift at the fail should be no larger
453 than the difference of their depths. */
454 if (!hasevery(fail->links, curr->links))
455 if (curr->depth - fail->depth < fail->shift)
456 fail->shift = curr->depth - fail->depth;
458 /* If the current node is accepting then the shift at the
459 fail and its descendents should be no larger than the
460 difference of their depths. */
461 if (curr->accepting && fail->maxshift > curr->depth - fail->depth)
462 fail->maxshift = curr->depth - fail->depth;
466 /* Traverse the trie in level order again, fixing up all nodes whose
467 shift exceeds their inherited maxshift. */
468 for (curr = kwset->trie->next; curr; curr = curr->next)
470 if (curr->maxshift > curr->parent->maxshift)
471 curr->maxshift = curr->parent->maxshift;
472 if (curr->shift > curr->maxshift)
473 curr->shift = curr->maxshift;
476 /* Create a vector, indexed by character code, of the outgoing links
477 from the root node. */
478 for (i = 0; i < NCHAR; ++i)
480 treenext(kwset->trie->links, next);
482 if ((trans = kwset->trans) != NULL)
483 for (i = 0; i < NCHAR; ++i)
484 kwset->next[i] = next[U(trans[i])];
486 memcpy(kwset->next, next, NCHAR * sizeof(struct trie *));
489 /* Fix things up for any translation table. */
490 if ((trans = kwset->trans) != NULL)
491 for (i = 0; i < NCHAR; ++i)
492 kwset->delta[i] = delta[U(trans[i])];
494 memcpy(kwset->delta, delta, NCHAR);
499 /* Fast boyer-moore search. */
501 bmexec (kwset_t kws, char const *text, size_t size)
503 struct kwset const *kwset;
504 unsigned char const *d1;
505 char const *ep, *sp, *tp;
506 int d, gc, i, len, md2;
508 kwset = (struct kwset const *) kws;
517 tp = memchr (text, kwset->target[0], size);
518 return tp ? tp - text : -1;
522 sp = kwset->target + len;
527 /* Significance of 12: 1 (initial offset) + 10 (skip loop) + 1 (md2). */
529 /* 11 is not a bug, the initial offset happens only once. */
530 for (ep = text + size - 11 * len;;)
534 d = d1[U(tp[-1])], tp += d;
535 d = d1[U(tp[-1])], tp += d;
538 d = d1[U(tp[-1])], tp += d;
539 d = d1[U(tp[-1])], tp += d;
540 d = d1[U(tp[-1])], tp += d;
543 d = d1[U(tp[-1])], tp += d;
544 d = d1[U(tp[-1])], tp += d;
545 d = d1[U(tp[-1])], tp += d;
548 d = d1[U(tp[-1])], tp += d;
549 d = d1[U(tp[-1])], tp += d;
555 for (i = 3; i <= len && U(tp[-i]) == U(sp[-i]); ++i)
558 return tp - len - text;
563 /* Now we have only a few characters left to search. We
564 carefully avoid ever producing an out-of-bounds pointer. */
569 d = d1[U((tp += d)[-1])];
574 for (i = 3; i <= len && U(tp[-i]) == U(sp[-i]); ++i)
577 return tp - len - text;
585 /* Hairy multiple string search. */
586 static size_t _GL_ARG_NONNULL ((4))
587 cwexec (kwset_t kws, char const *text, size_t len, struct kwsmatch *kwsmatch)
589 struct kwset const *kwset;
590 struct trie * const *next;
591 struct trie const *trie;
592 struct trie const *accept;
593 char const *beg, *lim, *mch, *lmch;
595 unsigned char const *delta;
597 char const *end, *qlim;
598 struct tree const *tree;
605 /* Initialize register copies and look for easy ways out. */
606 kwset = (struct kwset *) kws;
607 if (len < kwset->mind)
610 delta = kwset->delta;
611 trans = kwset->trans;
614 if ((d = kwset->mind) != 0)
618 mch = text, accept = kwset->trie;
622 if (len >= 4 * kwset->mind)
623 qlim = lim - 4 * kwset->mind;
627 while (lim - end >= d)
629 if (qlim && end <= qlim)
632 while ((d = delta[c = *end]) && end < qlim)
635 end += delta[U(*end)];
636 end += delta[U(*end)];
641 d = delta[c = (end += d)[-1]];
654 c = trans ? trans[U(*--beg)] : *--beg;
656 while (tree && c != tree->label)
680 /* Given a known match, find the longest possible match anchored
681 at or before its starting point. This is nearly a verbatim
682 copy of the preceding main search loops. */
683 if (lim - mch > kwset->maxd)
684 lim = mch + kwset->maxd;
687 while (lim - end >= d)
689 if ((d = delta[c = (end += d)[-1]]) != 0)
692 if (!(trie = next[c]))
697 if (trie->accepting && beg <= mch)
705 c = trans ? trans[U(*--beg)] : *--beg;
707 while (tree && c != tree->label)
715 if (trie->accepting && beg <= mch)
734 kwsmatch->index = accept->accepting / 2;
735 kwsmatch->offset[0] = mch - text;
736 kwsmatch->size[0] = accept->depth;
741 /* Search TEXT for a match of any member of the keyword set, KWS.
742 Return the offset (into TEXT) of the first byte of the matching substring,
743 or (size_t) -1 if no match is found. Upon a match, store details in
744 *KWSMATCH: index of matched keyword, start offset (same as the return
745 value), and length. */
747 kwsexec (kwset_t kws, char const *text, size_t size, struct kwsmatch *kwsmatch)
749 struct kwset const *kwset = (struct kwset *) kws;
750 if (kwset->words == 1 && kwset->trans == NULL)
752 size_t ret = bmexec (kws, text, size);
753 if (ret != (size_t) -1)
756 kwsmatch->offset[0] = ret;
757 kwsmatch->size[0] = kwset->mind;
762 return cwexec(kws, text, size, kwsmatch);
765 /* Free the components of the given keyword set. */
767 kwsfree (kwset_t kws)
771 kwset = (struct kwset *) kws;
772 obstack_free(&kwset->obstack, NULL);