No empty .Rs/.Re
[netbsd-mini2440.git] / gnu / dist / gettext / gettext-tools / libgrep / kwset.c
blobb87069043ae6383b068d1d470bcdf43cc57fb87c
1 /* kwset.c - search for any of a set of keywords.
2 Copyright 1989, 1998, 2000, 2005 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
7 any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
17 02111-1307, USA. */
19 /* Written August 1989 by Mike Haertel.
20 The author may be reached (Email) at the address mike@ai.mit.edu,
21 or (US mail) as Mike Haertel c/o Free Software Foundation. */
23 /* The algorithm implemented by these routines bears a startling resemblence
24 to one discovered by Beate Commentz-Walter, although it is not identical.
25 See "A String Matching Algorithm Fast on the Average," Technical Report,
26 IBM-Germany, Scientific Center Heidelberg, Tiergartenstrasse 15, D-6900
27 Heidelberg, Germany. See also Aho, A.V., and M. Corasick, "Efficient
28 String Matching: An Aid to Bibliographic Search," CACM June 1975,
29 Vol. 18, No. 6, which describes the failure function used below. */
31 #ifdef HAVE_CONFIG_H
32 # include <config.h>
33 #endif
34 #include <sys/types.h>
35 #include "kwset.h"
36 #include <limits.h>
37 #include <stdlib.h>
38 #include "obstack.h"
39 #include "gettext.h"
40 #define _(str) gettext (str)
42 #ifdef GREP
43 extern char *xmalloc();
44 # undef malloc
45 # define malloc xmalloc
46 #endif
48 #define NCHAR (UCHAR_MAX + 1)
49 #define obstack_chunk_alloc malloc
50 #define obstack_chunk_free free
52 /* Balanced tree of edges and labels leaving a given trie node. */
53 struct tree
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. */
63 struct trie
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. */
76 struct kwset
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. */
92 kwset_t
93 kwsalloc (char const *trans)
95 struct kwset *kwset;
97 kwset = (struct kwset *) malloc(sizeof (struct kwset));
98 if (!kwset)
99 return 0;
101 obstack_init(&kwset->obstack);
102 kwset->words = 0;
103 kwset->trie
104 = (struct trie *) obstack_alloc(&kwset->obstack, sizeof (struct trie));
105 if (!kwset->trie)
107 kwsfree((kwset_t) kwset);
108 return 0;
110 kwset->trie->accepting = 0;
111 kwset->trie->links = 0;
112 kwset->trie->parent = 0;
113 kwset->trie->next = 0;
114 kwset->trie->fail = 0;
115 kwset->trie->depth = 0;
116 kwset->trie->shift = 0;
117 kwset->mind = INT_MAX;
118 kwset->maxd = -1;
119 kwset->target = 0;
120 kwset->trans = trans;
122 return (kwset_t) kwset;
125 /* Add the given string to the contents of the keyword set. Return NULL
126 for success, an error message otherwise. */
127 const char *
128 kwsincr (kwset_t kws, char const *text, size_t len)
130 struct kwset *kwset;
131 register struct trie *trie;
132 register unsigned char label;
133 register struct tree *link;
134 register int depth;
135 struct tree *links[12];
136 enum { L, R } dirs[12];
137 struct tree *t, *r, *l, *rl, *lr;
139 kwset = (struct kwset *) kws;
140 trie = kwset->trie;
141 text += len;
143 /* Descend the trie (built of reversed keywords) character-by-character,
144 installing new nodes when necessary. */
145 while (len--)
147 label = kwset->trans ? kwset->trans[(unsigned char) *--text] : *--text;
149 /* Descend the tree of outgoing links for this trie node,
150 looking for the current character and keeping track
151 of the path followed. */
152 link = trie->links;
153 links[0] = (struct tree *) &trie->links;
154 dirs[0] = L;
155 depth = 1;
157 while (link && label != link->label)
159 links[depth] = link;
160 if (label < link->label)
161 dirs[depth++] = L, link = link->llink;
162 else
163 dirs[depth++] = R, link = link->rlink;
166 /* The current character doesn't have an outgoing link at
167 this trie node, so build a new trie node and install
168 a link in the current trie node's tree. */
169 if (!link)
171 link = (struct tree *) obstack_alloc(&kwset->obstack,
172 sizeof (struct tree));
173 if (!link)
174 return _("memory exhausted");
175 link->llink = 0;
176 link->rlink = 0;
177 link->trie = (struct trie *) obstack_alloc(&kwset->obstack,
178 sizeof (struct trie));
179 if (!link->trie)
180 return _("memory exhausted");
181 link->trie->accepting = 0;
182 link->trie->links = 0;
183 link->trie->parent = trie;
184 link->trie->next = 0;
185 link->trie->fail = 0;
186 link->trie->depth = trie->depth + 1;
187 link->trie->shift = 0;
188 link->label = label;
189 link->balance = 0;
191 /* Install the new tree node in its parent. */
192 if (dirs[--depth] == L)
193 links[depth]->llink = link;
194 else
195 links[depth]->rlink = link;
197 /* Back up the tree fixing the balance flags. */
198 while (depth && !links[depth]->balance)
200 if (dirs[depth] == L)
201 --links[depth]->balance;
202 else
203 ++links[depth]->balance;
204 --depth;
207 /* Rebalance the tree by pointer rotations if necessary. */
208 if (depth && ((dirs[depth] == L && --links[depth]->balance)
209 || (dirs[depth] == R && ++links[depth]->balance)))
211 switch (links[depth]->balance)
213 case (char) -2:
214 switch (dirs[depth + 1])
216 case L:
217 r = links[depth], t = r->llink, rl = t->rlink;
218 t->rlink = r, r->llink = rl;
219 t->balance = r->balance = 0;
220 break;
221 case R:
222 r = links[depth], l = r->llink, t = l->rlink;
223 rl = t->rlink, lr = t->llink;
224 t->llink = l, l->rlink = lr, t->rlink = r, r->llink = rl;
225 l->balance = t->balance != 1 ? 0 : -1;
226 r->balance = t->balance != (char) -1 ? 0 : 1;
227 t->balance = 0;
228 break;
229 default:
230 abort ();
232 break;
233 case 2:
234 switch (dirs[depth + 1])
236 case R:
237 l = links[depth], t = l->rlink, lr = t->llink;
238 t->llink = l, l->rlink = lr;
239 t->balance = l->balance = 0;
240 break;
241 case L:
242 l = links[depth], r = l->rlink, t = r->llink;
243 lr = t->llink, rl = t->rlink;
244 t->llink = l, l->rlink = lr, t->rlink = r, r->llink = rl;
245 l->balance = t->balance != 1 ? 0 : -1;
246 r->balance = t->balance != (char) -1 ? 0 : 1;
247 t->balance = 0;
248 break;
249 default:
250 abort ();
252 break;
253 default:
254 abort ();
257 if (dirs[depth - 1] == L)
258 links[depth - 1]->llink = t;
259 else
260 links[depth - 1]->rlink = t;
264 trie = link->trie;
267 /* Mark the node we finally reached as accepting, encoding the
268 index number of this word in the keyword set so far. */
269 if (!trie->accepting)
270 trie->accepting = 1 + 2 * kwset->words;
271 ++kwset->words;
273 /* Keep track of the longest and shortest string of the keyword set. */
274 if (trie->depth < kwset->mind)
275 kwset->mind = trie->depth;
276 if (trie->depth > kwset->maxd)
277 kwset->maxd = trie->depth;
279 return 0;
282 /* Enqueue the trie nodes referenced from the given tree in the
283 given queue. */
284 static void
285 enqueue (struct tree *tree, struct trie **last)
287 if (!tree)
288 return;
289 enqueue(tree->llink, last);
290 enqueue(tree->rlink, last);
291 (*last) = (*last)->next = tree->trie;
294 /* Compute the Aho-Corasick failure function for the trie nodes referenced
295 from the given tree, given the failure function for their parent as
296 well as a last resort failure node. */
297 static void
298 treefails (register struct tree const *tree, struct trie const *fail,
299 struct trie *recourse)
301 register struct tree *link;
303 if (!tree)
304 return;
306 treefails(tree->llink, fail, recourse);
307 treefails(tree->rlink, fail, recourse);
309 /* Find, in the chain of fails going back to the root, the first
310 node that has a descendent on the current label. */
311 while (fail)
313 link = fail->links;
314 while (link && tree->label != link->label)
315 if (tree->label < link->label)
316 link = link->llink;
317 else
318 link = link->rlink;
319 if (link)
321 tree->trie->fail = link->trie;
322 return;
324 fail = fail->fail;
327 tree->trie->fail = recourse;
330 /* Set delta entries for the links of the given tree such that
331 the preexisting delta value is larger than the current depth. */
332 static void
333 treedelta (register struct tree const *tree,
334 register unsigned int depth,
335 unsigned char delta[])
337 if (!tree)
338 return;
339 treedelta(tree->llink, depth, delta);
340 treedelta(tree->rlink, depth, delta);
341 if (depth < delta[tree->label])
342 delta[tree->label] = depth;
345 /* Return true if A has every label in B. */
346 static int
347 hasevery (register struct tree const *a, register struct tree const *b)
349 if (!b)
350 return 1;
351 if (!hasevery(a, b->llink))
352 return 0;
353 if (!hasevery(a, b->rlink))
354 return 0;
355 while (a && b->label != a->label)
356 if (b->label < a->label)
357 a = a->llink;
358 else
359 a = a->rlink;
360 return !!a;
363 /* Compute a vector, indexed by character code, of the trie nodes
364 referenced from the given tree. */
365 static void
366 treenext (struct tree const *tree, struct trie *next[])
368 if (!tree)
369 return;
370 treenext(tree->llink, next);
371 treenext(tree->rlink, next);
372 next[tree->label] = tree->trie;
375 /* Compute the shift for each trie node, as well as the delta
376 table and next cache for the given keyword set. */
377 const char *
378 kwsprep (kwset_t kws)
380 register struct kwset *kwset;
381 register int i;
382 register struct trie *curr, *fail;
383 register char const *trans;
384 unsigned char delta[NCHAR];
385 struct trie *last, *next[NCHAR];
387 kwset = (struct kwset *) kws;
389 /* Initial values for the delta table; will be changed later. The
390 delta entry for a given character is the smallest depth of any
391 node at which an outgoing edge is labeled by that character. */
392 if (kwset->mind < 256)
393 for (i = 0; i < NCHAR; ++i)
394 delta[i] = kwset->mind;
395 else
396 for (i = 0; i < NCHAR; ++i)
397 delta[i] = 255;
399 /* Check if we can use the simple boyer-moore algorithm, instead
400 of the hairy commentz-walter algorithm. */
401 if (kwset->words == 1 && kwset->trans == 0)
403 /* Looking for just one string. Extract it from the trie. */
404 kwset->target = obstack_alloc(&kwset->obstack, kwset->mind);
405 for (i = kwset->mind - 1, curr = kwset->trie; i >= 0; --i)
407 kwset->target[i] = curr->links->label;
408 curr = curr->links->trie;
410 /* Build the Boyer Moore delta. Boy that's easy compared to CW. */
411 for (i = 0; i < kwset->mind; ++i)
412 delta[(unsigned char) kwset->target[i]] = kwset->mind - (i + 1);
413 kwset->mind2 = kwset->mind;
414 /* Find the minimal delta2 shift that we might make after
415 a backwards match has failed. */
416 for (i = 0; i < kwset->mind - 1; ++i)
417 if (kwset->target[i] == kwset->target[kwset->mind - 1])
418 kwset->mind2 = kwset->mind - (i + 1);
420 else
422 /* Traverse the nodes of the trie in level order, simultaneously
423 computing the delta table, failure function, and shift function. */
424 for (curr = last = kwset->trie; curr; curr = curr->next)
426 /* Enqueue the immediate descendents in the level order queue. */
427 enqueue(curr->links, &last);
429 curr->shift = kwset->mind;
430 curr->maxshift = kwset->mind;
432 /* Update the delta table for the descendents of this node. */
433 treedelta(curr->links, curr->depth, delta);
435 /* Compute the failure function for the decendents of this node. */
436 treefails(curr->links, curr->fail, kwset->trie);
438 /* Update the shifts at each node in the current node's chain
439 of fails back to the root. */
440 for (fail = curr->fail; fail; fail = fail->fail)
442 /* If the current node has some outgoing edge that the fail
443 doesn't, then the shift at the fail should be no larger
444 than the difference of their depths. */
445 if (!hasevery(fail->links, curr->links))
446 if (curr->depth - fail->depth < fail->shift)
447 fail->shift = curr->depth - fail->depth;
449 /* If the current node is accepting then the shift at the
450 fail and its descendents should be no larger than the
451 difference of their depths. */
452 if (curr->accepting && fail->maxshift > curr->depth - fail->depth)
453 fail->maxshift = curr->depth - fail->depth;
457 /* Traverse the trie in level order again, fixing up all nodes whose
458 shift exceeds their inherited maxshift. */
459 for (curr = kwset->trie->next; curr; curr = curr->next)
461 if (curr->maxshift > curr->parent->maxshift)
462 curr->maxshift = curr->parent->maxshift;
463 if (curr->shift > curr->maxshift)
464 curr->shift = curr->maxshift;
467 /* Create a vector, indexed by character code, of the outgoing links
468 from the root node. */
469 for (i = 0; i < NCHAR; ++i)
470 next[i] = 0;
471 treenext(kwset->trie->links, next);
473 if ((trans = kwset->trans) != 0)
474 for (i = 0; i < NCHAR; ++i)
475 kwset->next[i] = next[(unsigned char) trans[i]];
476 else
477 for (i = 0; i < NCHAR; ++i)
478 kwset->next[i] = next[i];
481 /* Fix things up for any translation table. */
482 if ((trans = kwset->trans) != 0)
483 for (i = 0; i < NCHAR; ++i)
484 kwset->delta[i] = delta[(unsigned char) trans[i]];
485 else
486 for (i = 0; i < NCHAR; ++i)
487 kwset->delta[i] = delta[i];
489 return 0;
492 #define U(C) ((unsigned char) (C))
494 /* Fast boyer-moore search. */
495 static size_t
496 bmexec (kwset_t kws, char const *text, size_t size)
498 struct kwset const *kwset;
499 register unsigned char const *d1;
500 register char const *ep, *sp, *tp;
501 register int d, gc, i, len, md2;
503 kwset = (struct kwset const *) kws;
504 len = kwset->mind;
506 if (len == 0)
507 return 0;
508 if (len > size)
509 return -1;
510 if (len == 1)
512 tp = memchr (text, kwset->target[0], size);
513 return tp ? tp - text : -1;
516 d1 = kwset->delta;
517 sp = kwset->target + len;
518 gc = U(sp[-2]);
519 md2 = kwset->mind2;
520 tp = text + len;
522 /* Significance of 12: 1 (initial offset) + 10 (skip loop) + 1 (md2). */
523 if (size > 12 * len)
524 /* 11 is not a bug, the initial offset happens only once. */
525 for (ep = text + size - 11 * len;;)
527 while (tp <= ep)
529 d = d1[U(tp[-1])], tp += d;
530 d = d1[U(tp[-1])], tp += d;
531 if (d == 0)
532 goto found;
533 d = d1[U(tp[-1])], tp += d;
534 d = d1[U(tp[-1])], tp += d;
535 d = d1[U(tp[-1])], tp += d;
536 if (d == 0)
537 goto found;
538 d = d1[U(tp[-1])], tp += d;
539 d = d1[U(tp[-1])], tp += d;
540 d = d1[U(tp[-1])], tp += d;
541 if (d == 0)
542 goto found;
543 d = d1[U(tp[-1])], tp += d;
544 d = d1[U(tp[-1])], tp += d;
546 break;
547 found:
548 if (U(tp[-2]) == gc)
550 for (i = 3; i <= len && U(tp[-i]) == U(sp[-i]); ++i)
552 if (i > len)
553 return tp - len - text;
555 tp += md2;
558 /* Now we have only a few characters left to search. We
559 carefully avoid ever producing an out-of-bounds pointer. */
560 ep = text + size;
561 d = d1[U(tp[-1])];
562 while (d <= ep - tp)
564 d = d1[U((tp += d)[-1])];
565 if (d != 0)
566 continue;
567 if (U(tp[-2]) == gc)
569 for (i = 3; i <= len && U(tp[-i]) == U(sp[-i]); ++i)
571 if (i > len)
572 return tp - len - text;
574 d = md2;
577 return -1;
580 /* Hairy multiple string search. */
581 static size_t
582 cwexec (kwset_t kws, char const *text, size_t len, struct kwsmatch *kwsmatch)
584 struct kwset const *kwset;
585 struct trie * const *next;
586 struct trie const *trie;
587 struct trie const *accept;
588 char const *beg, *lim, *mch, *lmch;
589 register unsigned char c;
590 register unsigned char const *delta;
591 register int d;
592 register char const *end, *qlim;
593 register struct tree const *tree;
594 register char const *trans;
596 accept = NULL;
598 /* Initialize register copies and look for easy ways out. */
599 kwset = (struct kwset *) kws;
600 if (len < kwset->mind)
601 return -1;
602 next = kwset->next;
603 delta = kwset->delta;
604 trans = kwset->trans;
605 lim = text + len;
606 end = text;
607 if ((d = kwset->mind) != 0)
608 mch = 0;
609 else
611 mch = text, accept = kwset->trie;
612 goto match;
615 if (len >= 4 * kwset->mind)
616 qlim = lim - 4 * kwset->mind;
617 else
618 qlim = 0;
620 while (lim - end >= d)
622 if (qlim && end <= qlim)
624 end += d - 1;
625 while ((d = delta[c = *end]) && end < qlim)
627 end += d;
628 end += delta[(unsigned char) *end];
629 end += delta[(unsigned char) *end];
631 ++end;
633 else
634 d = delta[c = (end += d)[-1]];
635 if (d)
636 continue;
637 beg = end - 1;
638 trie = next[c];
639 if (trie->accepting)
641 mch = beg;
642 accept = trie;
644 d = trie->shift;
645 while (beg > text)
647 c = trans ? trans[(unsigned char) *--beg] : *--beg;
648 tree = trie->links;
649 while (tree && c != tree->label)
650 if (c < tree->label)
651 tree = tree->llink;
652 else
653 tree = tree->rlink;
654 if (tree)
656 trie = tree->trie;
657 if (trie->accepting)
659 mch = beg;
660 accept = trie;
663 else
664 break;
665 d = trie->shift;
667 if (mch)
668 goto match;
670 return -1;
672 match:
673 /* Given a known match, find the longest possible match anchored
674 at or before its starting point. This is nearly a verbatim
675 copy of the preceding main search loops. */
676 if (lim - mch > kwset->maxd)
677 lim = mch + kwset->maxd;
678 lmch = 0;
679 d = 1;
680 while (lim - end >= d)
682 if ((d = delta[c = (end += d)[-1]]) != 0)
683 continue;
684 beg = end - 1;
685 if (!(trie = next[c]))
687 d = 1;
688 continue;
690 if (trie->accepting && beg <= mch)
692 lmch = beg;
693 accept = trie;
695 d = trie->shift;
696 while (beg > text)
698 c = trans ? trans[(unsigned char) *--beg] : *--beg;
699 tree = trie->links;
700 while (tree && c != tree->label)
701 if (c < tree->label)
702 tree = tree->llink;
703 else
704 tree = tree->rlink;
705 if (tree)
707 trie = tree->trie;
708 if (trie->accepting && beg <= mch)
710 lmch = beg;
711 accept = trie;
714 else
715 break;
716 d = trie->shift;
718 if (lmch)
720 mch = lmch;
721 goto match;
723 if (!d)
724 d = 1;
727 if (kwsmatch)
729 kwsmatch->index = accept->accepting / 2;
730 kwsmatch->offset[0] = mch - text;
731 kwsmatch->size[0] = accept->depth;
733 return mch - text;
736 /* Search through the given text for a match of any member of the
737 given keyword set. Return a pointer to the first character of
738 the matching substring, or NULL if no match is found. If FOUNDLEN
739 is non-NULL store in the referenced location the length of the
740 matching substring. Similarly, if FOUNDIDX is non-NULL, store
741 in the referenced location the index number of the particular
742 keyword matched. */
743 size_t
744 kwsexec (kwset_t kws, char const *text, size_t size,
745 struct kwsmatch *kwsmatch)
747 struct kwset const *kwset = (struct kwset *) kws;
748 if (kwset->words == 1 && kwset->trans == 0)
750 size_t ret = bmexec (kws, text, size);
751 if (kwsmatch != 0 && ret != (size_t) -1)
753 kwsmatch->index = 0;
754 kwsmatch->offset[0] = ret;
755 kwsmatch->size[0] = kwset->mind;
757 return ret;
759 else
760 return cwexec(kws, text, size, kwsmatch);
763 /* Free the components of the given keyword set. */
764 void
765 kwsfree (kwset_t kws)
767 struct kwset *kwset;
769 kwset = (struct kwset *) kws;
770 obstack_free(&kwset->obstack, 0);
771 free(kws);